Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't Access Super Globals Inside __callStatic?

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?

like image 314
Xeoncross Avatar asked Dec 28 '22 09:12

Xeoncross


2 Answers

As indicated in the manual:

Note: Variable variables

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

(reference)

like image 131
Chris Baker Avatar answered Jan 05 '23 17:01

Chris Baker


[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();
like image 32
Tim G Avatar answered Jan 05 '23 15:01

Tim G