Ben Carey Ben Carey - 1 month ago 6
PHP Question

How to make variable global across entire class

Very simple question, is it possible to make a variable that is retrieved from outside of a class, 'global' to the whole class so that I do not have to call the 'global $variable' at the beginning of each method?

This is what I am currently doing:

class test{
public function testing(){
global $globalVariable,

// Do something
}
public function testing_two(){
global $globalVariable,

// Do something
}
}


In other words, can I import variables into the construct function and therefore make them accessible to the entire class without having to call 'global' for each method?

UPDATE

Not sure if I have made it too clear with what I would like to achieve. Please see below:

$globalVariable = 'hello';

class test{
public function testing(){
global $globalVariable,

// Do something
}
public function testing_two(){
global $globalVariable,

// Do something
}
}

Dan Dan
Answer

To clear up how to do it:

You most likely want to do something like this include('database.php');. At that very point everything you included there is global to your script. Now if you have a class like the above you add a constructor:

class testclass
{
    private $db;

    public function __construct($db)
    {
       $this->db = $db;
    }

    public function yourmethod()
    {
       $this->db->prepare(); // And so on
    }
}

Let's assume your global variable is called $db in the global scope. You can just construct your object now using new testclass($db);. When you now use $this->db in all your methods there is no need to use the global statement.