0

Main File;

$opid=$_GET['opid'];
include("etc.php");

etc.php;

function getTierOne() { ... }

I can use $opid variable before or after function but i can't use it in function, it returns undefined. What should i do to use it with a function in an included file?

1
  • global $opid; in the beginnig of the function Commented May 22, 2013 at 10:53

3 Answers 3

1
$getTierOne = function() use ($opid) {
  var_dump($opid);
};
Sign up to request clarification or add additional context in comments.

Comments

0

Its because the function only has local scope. It can only see variables defined within the function itself. Any variable defined outside the function can only be imported into the function or used globally.

There are several ways to do this, one of which is the global keyword:

$someVariable = 'someValue';

function getText(){
    global $someVariable;

    echo $someVariable;
    return;
}

getText();

However, I'd advise against this approach. What would happen if you changed $someVariable to another name? You'd have to go to each function you've imported it into and change it as well. Not very dynamic.

The other approach would be this:

$someVariable = 'someValue';

function getText($paramater1){
    return $parameter1;
}

echo getText($someVariable);

This is more logical, and organised. Passing the variable as an argument to the function is way better than using the global keyword within each function.

Alternatively, POST, REQUEST, SESSION and COOKIE variables are all superglobals. This means they can be used within functions without having to implicitly import them:

// Assume the value of $_POST['someText'] is someValue

function getText(){
   $someText = $_POST['someText'];
   return $someText;
}

echo getText();   // Outputs someValue

2 Comments

With global $opid it works for first function but not in others. There are five functions in included file.
Because you need to use the global keyword in each function you want to import that variable into. For instance: function testFunctionOne(){ global $someVariable; } function testFunctionTwo(){ global $someVariable; } As you can see, having to use a global keyword for each function isn't really practical, check this out: stackoverflow.com/questions/1557787/…
0
function getTierOne() 
{ 
     global $opid;
     //...
}

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.