PHP构造函数中的全局变量 [英] Global variable inside a constructor with PHP
本文介绍了PHP构造函数中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这应该很明显,但是我对PHP变量范围有些困惑.
This should be obvious, but I'm getting a bit confused about PHP variable scope.
我在构造函数中有一个变量,以后我想在同一类的函数中使用该变量.我当前的方法是这样:
I have a variable inside a Constructor, which I want to use later in a function in the same class. My current method is this:
<?php
class Log(){
function Log(){
$_ENV['access'] = true;
}
function test(){
$access = $ENV['access'];
}
}
?>
有没有比滥用环境变量更好的方法了?谢谢.
Is there a better way to do this than abusing environment variables? Thanks.
推荐答案
您可以使用类变量,该类变量具有... class的上下文:
(当然是PHP 5的示例;我已经重写了几件事,因此您的代码更加符合PHP5)
You could use a class variable, which has a context of... a class :
(Example for PHP 5, of course ; I've re-written a few things so your code is more PHP5-compliant)
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;
}
}
您应该看一下:
- PHP手册的类和对象"部分
- 对于这个特定问题,请参见属性
- The "Classes and Objects" section of the PHP manual
- And, for this specific question, the sub-section Properties
这篇关于PHP构造函数中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文