这应该是显而易见的,但我对
PHP变量范围有点困惑.
我在构造函数中有一个变量,我想稍后在同一个类的函数中使用它.我目前的方法是这样的:
<?PHP
class Log(){
function Log(){
$_ENV['access'] = true;
}
function test(){
$access = $ENV['access'];
}
}
?>
有没有比滥用环境变量更好的方法呢?谢谢.
你可以使用一个类变量,它有一个类的上下文:
(当然,PHP 5的示例;我重写了一些内容,因此您的代码更符合PHP5)
(当然,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;
}
}
你应该看看:
> The “Classes and Objects” section of the PHP manual
>并且,对于这个具体问题,分段Properties