不能访问__callStatic中的超级全局变量


Can't Access Super Globals Inside __callStatic?

下面的代码在我的PHP 5.3.6-13ubuntu3.2安装上失败了,这让我想知道为什么我不能在这个方法中访问$_SERVER Super Global。

<?php
header('Content-Type: text/plain');
$method = '_SERVER';
var_dump($$method); // Works fine
class i
{
    public static function __callStatic($method, $args)
    {
        $method = '_SERVER';
        var_dump($$method); // Notice: Undefined variable: _SERVER
    }
}
i::method();

有人知道这是怎么回事吗?

如手册所示:

Note: Variable variables
Superglobals cannot be used as variable variables inside functions or class methods. 

(引用)

[edit -添加了一个可能的解决方法]

header('Content-Type: text/plain');
class i
{
    public static function __callStatic( $method, $args)
    {
        switch( $method )
        {
        case 'GLOBALS':
            $var =& $GLOBALS;
            break;
        case '_SERVER':
            $var =& $_SERVER;
            break;
        case '_GET':
            $var =& $_GET;
            break;
        // ...
        default:
            throw new Exception( 'Undefined variable.' );
        }
        var_dump( $var );
    }
}
i::_SERVER();
i::_GET();

(原来的答案)这太奇怪了。我同意这可能是一个PHP bug。但是,超全局变量是可以工作的,只是不能作为一个变量。

<?php
header('Content-Type: text/plain');
$method = '_SERVER';
var_dump($$method); // Works fine
class i
{
    public static function __callStatic( $method, $args)
    {
        var_dump( $_SERVER ); // works
        var_dump( $$method ); // Notice: Undefined variable: _SERVER
    }
}
i::_SERVER();
相关文章: