【问题标题】:PHP use variable from global space inside classPHP使用类内全局空间中的变量
【发布时间】: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]。我们可以轻松查看问题是否有答案,以及答案是否已被接受。

标签: php class scope


【解决方案1】:

尝试将$myvar 称为超全局:

private static $container = $GLOBALS['myvar'];

尽管正如 Ron Dadon 所指出的,这在 OOP 中通常是不好的做法。

编辑:

我在这里开枪了。我上面的解决方案实际上不起作用,至少不适合我。因此,实现这一目标的更好方法如下:

$myvar = array_merge($plantask_global_script, $plantask_global_config);

class Env implements ArrayAccess
{
    private static $container = null;

    public static function init($var)
    {
        self::$container = $var;
    }

    ...
}

Env::init($myvar);

【讨论】:

  • 非常感谢,我现在可以关闭了。 :)
  • 请看我的编辑。我相信我最初的建议实际上并不奏效。我想确保您的问题得到正确回答:)
猜你喜欢
  • 1970-01-01
  • 2012-12-28
  • 1970-01-01
  • 2012-12-26
  • 1970-01-01
  • 2012-03-13
  • 2019-08-11
  • 1970-01-01
  • 2012-01-19
相关资源
最近更新 更多