【发布时间】:2015-08-04 11:28:09
【问题描述】:
有两个类,每个类都在自己的文件中:
<?php
namespace test;
class calledClass {
private $Variable;
function __construct() {
global $testVar;
require_once 'config.php';
$this->Variable = $testVar;
echo "test var: ".$this->Variable;
}
}
?>
和
<?php
namespace test;
class callingClass {
function __construct() {
require_once 'config.php';
require_once 'calledClass.php';
new calledClass();
}
}
new callingClass();
?>
和简单的config.php:
<?php
namespace test;
$testVar = 'there is a test content';
?>
当我启动callingClass.php(创建对象calledClass)时,calledClass 中的属性$Variable 为空。但是当我手动启动calledClass.php 时,它会从config.php 读取含义$testVar,并将其假定为$Variable。
如果我在 callingClass 中将 $testVar 声明为 global,这会有所帮助 - calledClass 可以从 config.php 读取 $testVar。
谁能告诉我为什么从另一个对象创建的对象不能将变量声明为全局变量并使用它们?
【问题讨论】:
-
除此之外,这将是非常糟糕的做法,而且不是 OOP,而且您正在做的还有无数其他问题;
$testVar在调用类构造函数中不是全局的,只是该方法中的局部范围变量 -
谢谢。在类中使用配置文件的更好方法是什么(除了将变量作为函数的参数传递)?
parse_ini_file?
标签: php class global-variables