这应该是显而易见的,但我对PHP变量范围有点困惑.
我在构造函数中有一个变量,我想稍后在同一个类的函数中使用它.我目前的方法是这样的:
<?php
class Log(){
function Log(){
$_ENV['access'] = true;
}
function test(){
$access = $ENV['access'];
}
}
?>
Run Code Online (Sandbox Code Playgroud)
有没有比滥用环境变量更好的方法呢?谢谢.
Pas*_*TIN 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;
}
}
Run Code Online (Sandbox Code Playgroud)
你应该看看: