PHP class: Global variable as property in class

188,613

Solution 1

You probably don't really want to be doing this, as it's going to be a nightmare to debug, but it seems to be possible. The key is the part where you assign by reference in the constructor.

$GLOBALS = array(
    'MyNumber' => 1
);

class Foo {
    protected $glob;

    public function __construct() {
        global $GLOBALS;
        $this->glob =& $GLOBALS;
    }

    public function getGlob() {
        return $this->glob['MyNumber'];
    }
}

$f = new Foo;

echo $f->getGlob() . "\n";
$GLOBALS['MyNumber'] = 2;
echo $f->getGlob() . "\n";

The output will be

1
2

which indicates that it's being assigned by reference, not value.

As I said, it will be a nightmare to debug, so you really shouldn't do this. Have a read through the wikipedia article on encapsulation; basically, your object should ideally manage its own data and the methods in which that data is modified; even public properties are generally, IMHO, a bad idea.

Solution 2

Try to avoid globals, instead you can use something like this

class myClass() {
 private $myNumber;

 public function setNumber($number) {
  $this->myNumber = $number;
 }
}

Now you can call

$class = new myClass();
$class->setNumber('1234');

Solution 3

Simply use the global keyword.

e.g.:

class myClass() {
    private function foo() {
        global $MyNumber;
        ...

$MyNumber will then become accessible (and indeed modifyable) within that method.

However, the use of globals is often frowned upon (they can give off a bad code smell), so you might want to consider using a singleton class to store anything of this nature. (Then again, without knowing more about what you're trying to achieve this might be a very bad idea - a define could well be more useful.)

Solution 4

What I've experienced is that you can't assign your global variable to a class variable directly.

class myClass() {

    public $var = $GLOBALS['variable'];

    public function func() {
         var_dump($this->var);
    }
}

With the code right above, you get an error saying "Parse error: syntax error, unexpected '$GLOBALS'"

But if we do something like this,

class myClass() {

    public $var = array();

    public function __construct() {
        $this->var = $GLOBALS['variable'];
    }

    public function func() {
         var_dump($this->var);
    }

}

Our code will work fine.

Where we assign a global variable to a class variable must be inside a function. And I've used constructor function for this.

So, you can access your global variable inside the every function of a class just using $this->var;

Solution 5

What about using constructor?

class myClass {

   $myNumber = NULL;

   public function __construct() {
      global myNumber;

      $this->myNumber = &myNumber; 
   }

   public function foo() {
      echo $this->myNumber;
   }

}

Or much better this way (passing the global variable as parameter when inicializin the object - read only)

class myClass {

   $myNumber = NULL;

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

   public function foo() {
      echo $this->myNumber;
   }

}
$instance = new myClass($myNumber);
Share:
188,613
Zebra
Author by

Zebra

Updated on May 07, 2021

Comments

  • Zebra
    Zebra almost 3 years

    I have a global variable outside my class = $MyNumber;


    How do I declare this as a property in myClass?
    For every method in my class, this is what I do:

    class myClass() {
    
        private function foo() {
             $privateNumber = $GLOBALS['MyNumber'];
        }
    
    }
    



    I want this

    class myClass() {
    
        //What goes here?
        var $classNumber = ???//the global $MyNumber;
    
        private function foo() {
             $privateNumber = $this->classNumber;
        }
    
    }
    



    EDIT: I want to create a variable based on the global $MyNumber but
    modified before using it in the methods

    something like: var $classNumber = global $MyNumber + 100;

  • i_a
    i_a about 9 years
    Thanks. Yes, can be a nightmare to debug. But if don't want to write the global keyword for the variable in every method in the class, and you still want it to represent the original global variable (in case its state changes outside of the class), this solution looks good. Thanks!
  • El Yobo
    El Yobo about 9 years
    Yes it will work, but having the global variable at all is best avoided if at all possible.
  • JasonXA
    JasonXA over 8 years
    Well sure, but it can be useful for settings global config vars, if they're unique and static, without having to explicitly call a method like mrwooster's example. For instance, URI's, access tokens, passwords etc, which inside an app will be used either way. Basically calling a method to initialize a variable "by hand" that way is redundant unless you know that data to be dynamic.
  • El Yobo
    El Yobo about 8 years
    Or better, don't have global (in the PHP sense) config vars at all. Inject a container of some sort for your configuration and pass that to the places that need it.
  • dev0
    dev0 over 6 years
    Please use proper formatting and don't post code only, elaborate on your answer.