PHP class: Global variable as property in class

后端 未结 7 1129
囚心锁ツ
囚心锁ツ 2020-12-05 13:03

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

7条回答
  •  遥遥无期
    2020-12-05 13:42

    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.

提交回复
热议问题