Global variable inside a constructor with PHP

前端 未结 3 1513
情话喂你
情话喂你 2021-01-18 10:50

This should be obvious, but I\'m getting a bit confused about PHP variable scope.

I have a variable inside a Constructor, which I want to use later in a function in

3条回答
  •  时光说笑
    2021-01-18 10:59

    You could use the global keyword:

    class Log{
        protected $access;
        function Log(){
            global $access;
            $this->access = &$access;
        }
    }
    

    But you really should be passing the variable in the constructor:

    class Log{
        protected $access;
        function Log($access){
            $this->access = &$access;
        }
        //...Then you have access to the access variable throughout the class:
        function test(){
            echo $this->access;
        }
    }
    

提交回复
热议问题