milesh
milesh

Reputation: 570

PHP using variable in an included function

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?

Upvotes: 0

Views: 67

Answers (3)

Phil Cross
Phil Cross

Reputation: 9302

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

Upvotes: 0

elclanrs
elclanrs

Reputation: 94151

$getTierOne = function() use ($opid) {
  var_dump($opid);
};

Upvotes: 1

Maxim Khan-Magomedov
Maxim Khan-Magomedov

Reputation: 1336

function getTierOne() 
{ 
     global $opid;
     //...
}

Upvotes: 0

Related Questions