从构造php访问全局变量

时间:2016-12-24 05:01:59

标签: php global

我想在__construct()中声明全局变量,并从另一个公共函数访问它。

class NewMineClass(){
   public function __construct(){
     global $goaway;
   }

   public function imHere(){
     $this->goaway;
   }
}

但它不起作用。

1 个答案:

答案 0 :(得分:2)

class properties。我想我最好通过一个例子来解释:

// Note that the class name needs no parenthesis 
class NewMineClass
{   
    // This is a class property, it's accessible within the class scope.
    // All the methods of this class can access it using `$this->goaway`.
    // If you want it to be accessible from outside the class, you need
    // to declare it as public instead of protected.
    protected $goaway;

    public function __construct()
    {
        $this->goaway = 'something i want to initialize in the constructor';
    }

    public function imHere()
    {
        echo $this->goaway;
        // Prints: something i want to initialize in the constructor
    }
}

我鼓励您阅读有关PHP OOP概念的内容: