views:

308

answers:

5

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

+1  A: 

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.

Chacha102
Thanks Chacha102.
John
+3  A: 

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.

Ilya Biryukov
+2  A: 

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?

Robert Elwell
In newer versions of PHP you don't even need __construct() - you can create a function with the name of the class and it behaves as the constructor.For example, say you have a class called TestClass class TestClass { private x; function TestClass(y) { this->x = y; } }This would be a valid constructor.But I agree...I would pass it into the constructor.
Joe Morgan
Joe Morgan, I'm pretty sure it was that older versions didn't support the __construct magic method, and **required** the constructor to share the class's name.
eyelidlessness
Argh, stupid broken half-Markdown. That was the `__construct` magic method.
eyelidlessness
And I knew the name of his class how?
Robert Elwell
+2  A: 

Hi,

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...

Pascal MARTIN
A: 

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

inakiabt