PHP 类中的命名空间和全局变量问题
我陷入了这种困惑,我不明白为什么我的 HelperClass() 下的全局 $error 返回空,我可以验证 $class->error 确实之前已填充了数据。
在这种情况下,命名空间是否存在某种我不知道的问题?请给我一些指点。
以下是一些相关的代码。
在主文件下
namespace Core;
$class = new ControllerClass();
$error = $class->error;
// verified that $error prints correctly here
include ViewFile.php;
ViewFile.php 下
$helper = new HelperClass();
// __autoload function took care of the include
HelperClass 下:
namespace Core\Skeleton;
class HelperClass {
public function __construct() {
global $error;
// $error != $class->error as defined earlier
// $error is empty here
}
I am stuck with this confusion where I don't understand why my global $error under my HelperClass() returns empty, where I could verify that $class->error is indeed filled up with data earlier on.
Is there some sort of issues with namespace in this case that I am not aware about? Please give me some pointers.
Here are some of the codes that are relevant.
Under Main file
namespace Core;
$class = new ControllerClass();
$error = $class->error;
// verified that $error prints correctly here
include ViewFile.php;
Under ViewFile.php
$helper = new HelperClass();
// __autoload function took care of the include
Under HelperClass:
namespace Core\Skeleton;
class HelperClass {
public function __construct() {
global $error;
// $error != $class->error as defined earlier
// $error is empty here
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用自动加载器或在另一个辅助函数中包含您的类,则
$error
变量从未在“全局”作用域中声明。它最终出现在一些地方,并被处理掉。在为它赋值之前声明它是共享的。
另外,虽然共享变量本身没有任何问题。名称
$error
似乎有点太通用了。也许您可以使用一个不那么模糊或更结构化的交换变量。$GLOBALS["/var/log"]["controller_error"]
或一些数组。If you're using an autoloader or include your classes from within another helper function, then the
$error
variable was never declared in the 'global' scope. It ended up in some local, and got disposed.Declare it shared right before you assign it a value.
Also while there is nothing wrong with shared variables per se. The name
$error
seems slightly too generic. Maybe you can up with a less ambigious or more structured exchange variable.$GLOBALS["/var/log"]["controller_error"]
or something arrayish.