PHP中构造函数内的全局变量
发布时间:2020-12-13 17:50:34 所属栏目:PHP教程 来源:网络整理
导读:这应该是显而易见的,但我对 PHP变量范围有点困惑. 我在构造函数中有一个变量,我想稍后在同一个类的函数中使用它.我目前的方法是这样的: ?phpclass Log(){ function Log(){ $_ENV['access'] = true; } function test(){ $access = $ENV['access']; }}? 有没
这应该是显而易见的,但我对
PHP变量范围有点困惑.
我在构造函数中有一个变量,我想稍后在同一个类的函数中使用它.我目前的方法是这样的: <?php class Log(){ function Log(){ $_ENV['access'] = true; } function test(){ $access = $ENV['access']; } } ?> 有没有比滥用环境变量更好的方法呢?谢谢.
你可以使用一个类变量,它有一个类的上下文:
(当然,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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |