Jay
Jay

Reputation: 11179

PHP - accessing global variables in all functions of class

I need to access some variables of an external php file in most of functions of a class. I'm accessing in following way (and it works fine)

class test{

function a(){ 
    global $myglobalvar ;
    ..
    ..
    }

function b(){ 
    global $myglobalvar ;
    ..
    ..
    }

function c(){ 
    global $myglobalvar ;
    ..
    ..
    }

}

Is there a way that i can access $myglobalvar in all functions of the class without declaring in each function? I did read that it can be done by declaring only once in the constructor of the class, but I dont know how to do it. Thanks for any help.

Upvotes: 3

Views: 12023

Answers (3)

Prisoner
Prisoner

Reputation: 27618

class test{

 private $myglobalvar;

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

 function a(){ 
  echo $this->myglobalvar;
 }

 function b(){ 
  echo $this->myglobalvar; 
 }

 function c(){ 
  echo $this->myglobalvar;
 }

}

$test = new test("something");
$test->a(); // echos something
$test->b(); // echos something
$test->c(); // echos something

Upvotes: 14

markus
markus

Reputation: 40675

If you tell us more about this case, we might be able to tell you a better way to solve your problem. Globals should be avoided, whenever possible. Are you really talking about a variable or is it more like a configuration option that stays the same during a whole server roundtrip. In that case you could think of treating it like a configuration option and store it in a registry object (singleton).

Upvotes: 2

mario
mario

Reputation: 145472

You can create a reference to a global variable in the constructor (much like global would):

class test{

    function __construct() { 
        $this->myglobalvar = & $GLOBALS["myglobalvar"];

Which then allows aceess to the global via $this->myglobalvar in each method.

Upvotes: 5

Related Questions