PHP 类中的命名空间和全局变量问题

发布于 2024-12-19 13:44:07 字数 682 浏览 0 评论 0原文

我陷入了这种困惑,我不明白为什么我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心不设防 2024-12-26 13:44:07

如果您使用自动加载器或在另一个辅助函数中包含您的类,则 $error 变量从未在“全局”作用域中声明。它最终出现在一些地方,并被处理掉。

在为它赋值之前声明它是共享的。

namespace Core;
$class = new ControllerClass();
global $error;
$error = $class->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.

namespace Core;
$class = new ControllerClass();
global $error;
$error = $class->error;

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文