PHP - access to global variables in all class functions

I need to access some variables of an external php file in most class functions. I have access as follows (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 a class without declaring in each function? I read that this can be done by declaring only once in the class constructor, but I do not know how to do this. Thanks for any help.

+3
source share
3 answers
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
+14
source

You can create a reference global variable in the constructor (same as global):

class test{

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

which then allows aceess globally through $this->myglobalvarin each method.

+4

If you tell us more about this case, we can tell you the best way to solve your problem. Whenever possible, globals should be avoided. Are you really talking about a variable or more like a configuration parameter that stays the same throughout the server? In this case, you might consider looking at it as a configuration parameter and storing it in a registry object (singleton).

+2
source

Source: https://habr.com/ru/post/1796669/


All Articles