我从PHP开始使用OOP,我遇到了全局变量的问题。
我目前的结构示例:
test.php
需要globals.php
并且还包括classes.php
。
globals.php
有以下代码:
global $something;
$something = "my text";
和classes.php
看起来像这样:
global $something;
class myClass {
public $abc = "123";
public $something;
public function doSomething() {
echo $this->abc."<br>";
echo $this->something;
}
}
$class = new myClass();
$class_Function = $class->doSomething();
print_r($class_Function);
最后,test.php
仅显示“123”。
我尝试使用“include()”代替globals.php
的“require”但是没有用。在globals.php
中也没有包含classes.php
。
答案 0 :(得分:3)
$this->something
从未初始化。全局$something
完全超出范围,与类属性$this->something
无关。如果需要访问函数或方法中的全局函数,则需要将其声明为全局:
public function doSomething() {
global $something;
echo $this->abc."<br>";
echo $something;
}
但是你需要停止使用全局变量,因为这不是一个好的解决方案。如果您需要定义一些对您的系统来说是全局的常量值,则首选使用define()
define("SOMETHING","My text")
然后您可以在代码的任何部分访问它:
echo SOMETHING;
另见:PHP global variable scope inside a class 和Use external variable inside PHP class