PHP class: Global variable as property in class

后端 未结 7 1141
囚心锁ツ
囚心锁ツ 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

    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;

提交回复
热议问题