【发布时间】:2015-08-14 08:24:30
【问题描述】:
您好,我正在用 PHP 编写一些代码。我需要在我的类中使用全局范围内的变量,但它不起作用。我不知道我是否需要使用命名空间以及如何使用?谢谢 示例:
<?PHP
$plantask_global_script = array("one", "two");
$plantask_global_config = array("three", "four");
$myvar = array_merge($plantask_global_script, $plantask_global_config);
class Env implements ArrayAccess
{
static private $container = $myvar;
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
self::$container[] = $value;
} else {
self::$container[$offset] = $value;
}
}
public function offsetExists($offset)
{
return isset(self::$container[$offset]);
}
public function offsetUnset($offset)
{
unset(self::$container[$offset]);
}
public function offsetGet($offset)
{
return isset(self::$container[$offset]) ? self::$container[$offset] : null;
}
}
【问题讨论】:
-
尝试在类的第一行添加代码:global $myvar;
-
顺便说一下,全局变量通常不是很好的 OOP 实践,它们会使你的类与全局变量紧密耦合
-
为了避免 $GLOBALS,您可以创建一个 getter 和一个 setter 方法来在类中使用该值。
-
我建议您从标题中删除
[answered]。我们可以轻松查看问题是否有答案,以及答案是否已被接受。