Can't Access Super Globals Inside __callStatic?

我的梦境 提交于 2019-12-10 16:18:31

问题


The following code fails on my install of PHP 5.3.6-13ubuntu3.2 which makes me wonder why I can't access the $_SERVER Super Global inside this method.

<?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();

Anyone know what is wrong here?


回答1:


As indicated in the manual:

Note: Variable variables

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

(reference)




回答2:


[edit - added a possible workaround]

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();

[original answer] This is weird. I agree that it may be a PHP bug. However, the superglobal does work, just not as a variable variable.

<?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();


来源:https://stackoverflow.com/questions/8404741/cant-access-super-globals-inside-callstatic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!