PHP名字空间和类中的全局变量问题 [英] PHP Namespace and global variable issue within classes

查看:126
本文介绍了PHP名字空间和类中的全局变量问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我陷入了这种困惑,我不明白为什么我的HelperClass()下的全局$错误返回空,我可以验证$ class->错误确实已经充满了数据。



在这种情况下,我没有意识到命名空间是否存在某些问题?请给我一些指示。



以下是一些相关的代码。



在主文件中

  namespace核心; 
$ class = new ControllerClass();
$ error = $ class->错误;
//验证$错误在这里正确打印
包含ViewFile.php; b


$ b

> $ helper = new HelperClass();
// __autoload函数负责包含

在HelperClass下:

  namespace Core \Skeleton; 

class HelperClass {
public function __construct(){
global $ error;
// $ error!= $ class->前面定义的错误
// $ error在这里为空
}
$($ p

解决方案错误变量从未在'全局'范围内声明。它在一些地方结束了,并被处置掉。



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

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

另外,虽然共享变量本身没有问题。名称 $ error 看起来有些过于通用。也许你可以用一个不太具有吸引力或更具结构性的交换变量。 $ GLOBALS [/ var / log] [controller_error] 或者其他数组。


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
}

解决方案

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.

这篇关于PHP名字空间和类中的全局变量问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆