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

标签 php namespaces global-variables

我陷入了这种困惑,我不明白为什么我的 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
}

最佳答案

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

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

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

此外,共享变量本身并没有错。名称 $error 似乎有点过于通用。也许您可以使用一个不那么模糊或更结构化的交换变量。 $GLOBALS["/var/log"]["controller_error"] 或类似数组的内容。

关于类中的 PHP 命名空间和全局变量问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8374947/

相关文章:

php - 为什么 PHP 在命名空间中找不到我的类

php - PHP 中文件父目录的完整绝对路径

命名空间范围变量的 C++ 初始化

linux - 导出后无法在函数外使用局部变量

node.js - typescript 阻止导出在全局范围内可用?

c# - 警告 “The type X in Y.cs conflicts with the imported type X in Z.dll”

php - SQL 结果中的排序优先级

php - 登录用户在 PHP session 中切换到另一个用户

php - 如何将数据从 MySQL 传递到 Google map

PHP 查找数组的所有(有点)唯一组合