Search code examples
phpclassvariablesmethods

PHP class: Global variable as property in class


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;


Solution

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