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?

milesh
  • 470
  • 3
  • 8
  • 18

3 Answers3

1
$getTierOne = function() use ($opid) {
  var_dump($opid);
};
elclanrs
  • 85,039
  • 19
  • 126
  • 159
0
function getTierOne() 
{ 
     global $opid;
     //...
}
Maxim Khan-Magomedov
  • 1,276
  • 11
  • 13
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
Phil Cross
  • 8,241
  • 10
  • 43
  • 76
  • With `global $opid` it works for first function but not in others. There are five functions in included file. – milesh May 22 '13 at 11:18
  • 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: http://stackoverflow.com/questions/1557787/are-global-variables-in-php-considered-bad-practice-if-so-why – Phil Cross May 22 '13 at 11:22