0

How to pass a $_GET variable into function?

$_GET['TEST']='some word';
public function example() {       
   //pass $_GET['TEST'] into here
}

When I try to access $_GET['TEST'] in my function, it is empty.

2
  • 4
    This is flawed. This is not a function but a method...where is your class? Commented Jun 1, 2011 at 10:51
  • 2
    I think you should understand the very basics of php variables, php functions and general OOP. Commented Jun 1, 2011 at 10:52

6 Answers 6

4

The $_GET array is one of PHPs superglobals so you can use it as-is within the function:

public function example() {       
   print $_GET['TEST'];
}

In general, you pass a variable (argument) like so:

public function example($arg1) {       
   print $arg1;
}
example($myNonGlobalVar);
Sign up to request clarification or add additional context in comments.

Comments

1

If this is a function and not an object method then you pass the parameter like so

function example($test) {
    echo $test;
}

and then you call that function like so

$_GET['test'] = 'test';
example($_GET['test']);

output being

test

However if this is an object you could do this

class Test {

    public function example($test) {
        echo $test;
    }
}

and you would then call it like so

$_GET['test'] = 'test';
$testObj = new Test;
$testObj->example($_GET['test']);

and the output should be

test

I hope this helps you out.

Comments

0

First of all - you should not set anything to superglobals ($_GET, $_POST, etc).

So we convert it to:

$test = 'some word';

And if you want to pass it to the function just do something like:

function example($value) {       
   echo $value;
}

And call this function with:

example($test);

Comments

0
function example ($value) {
  $value; // available here
}
example($_GET['TEST']);

Comments

0
function example($parameter)
{
     do something with $parameter;
}

$variable = 'some word';

example($variable);

Comments

0

Simply declare the value for the variable by

declare the function by

function employee($name,$email) {
 // function statements
}

$name = $_GET["name"];
$email = $_GET["email"];

calling the function by

employee($name,$email);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.