PHP中构造函数内的全局变量

时间:2009-12-18 12:13:47

标签: php oop scope

这应该是显而易见的,但我对PHP变量范围感到有点困惑。

我在构造函数中有一个变量,我想稍后在同一个类的函数中使用它。我目前的方法是:

<?php

class Log(){

   function Log(){
      $_ENV['access'] = true;
   }

   function test(){
      $access = $ENV['access'];
   }

}

?>

有没有比滥用环境变量更好的方法呢?感谢。

3 个答案:

答案 0 :(得分:18)

你可以使用一个类变量,它有一个类的上下文:
(当然是PHP 5的示例;我重写了一些内容,因此您的代码更符合PHP5标准)

class Log {
   // Declaration of the propery
   protected $_myVar;

   public function __construct() {
      // The property is accessed via $this->nameOfTheProperty :
      $this->_myVar = true;
   }

   public function test() {
      // Once the property has been set in the constructor, it keeps its value for the whole object :
      $access = $this->_myVar;
   }

}

你应该看看:

答案 1 :(得分:3)

全球被认为是有害的。如果这是外部依赖项,请将其传递给构造函数并将其保存在属性中以供以后使用。如果您只需要在调用test期间设置它,您可能需要考虑将其作为该方法的参数。

答案 2 :(得分:0)

您可以使用全局关键字:

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

但是你真的应该在构造函数中传递变量:

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;
    }
}