Question

In PHP, how do you use an external $var for use within a function in a class? For example, say $some_external_var sets to true and you have something like

class myclass {
bla ....
bla ....

function myfunction()  {

  if (isset($some_external_var)) do something ...

   } 

}


$some_external_var =true;

$obj = new myclass();
$obj->myfunction();

Thanks

Was it helpful?

Solution

Global $some_external_var;

function myfunction()  {
  Global $some_external_var;
  if (!empty($some_external_var)) do something ...

   } 

}

But because Global automatically sets it, check if it isn't empty.

OTHER TIPS

You'll need to use the global keyword inside your function, to make your external variable visible to that function.

For instance :

$my_var_2 = 'glop';

function test_2()
{
    global $my_var_2;
    var_dump($my_var_2);  // string 'glop' (length=4)
}

test_2();

You could also use the $GLOBALS array, which is always visible, even inside functions.


But it is generally not considered a good practice to use global variables: your classes should not depend on some kind of external stuff that might or might not be there !

A better way would be to pass the variables you need as parameters, either to the methods themselves, or to the constructor of the class...

that's bad software design. In order for a class to function, it needs to be provided with data. So, pass that external var into your class, otherwise you're creating unnecessary dependencies.

Why don't you just pass this variable during __construct() and make what the object does during construction conditional on the truth value of that variable?

Use Setters and Getters or maybe a centralized config like:

function config()
{
  static $data;

  if(!isset($data))
  {
    $data = new stdClass();
  }

  return $data;
}

class myClass
{
    public function myFunction()
    {
        echo "config()->myConfigVar: " . config()->myConfigVar;
    }
}

and the use it:

config()->myConfigVar = "Hello world";

$myClass = new myClass();
$myClass->myFunction();

http://www.evanbot.com/article/universally-accessible-data-php/24

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top