RSS Feed

Peter Goodman's blog about PHP, Parsing Theory, C++, Functional Programming, Applications,

Controlling PHP's Superglobals

It's summer again. Summer means coding PHP at work and having time to my own things. Speaking of which, here's a fun little hack I just came up with: http://codepad.org/aNW13yC9.

<?php

error_reporting(E_ALL | E_STRICT);

/**
 * Class that becomes a super global variable.
 * @author Peter Goodman
 */
final class SuperGlobal implements ArrayAccess {
    public $globals = array();

    public function __construct(&$globals) {
        $this->globals = &$globals;
    }

    public function offsetGet($key) {
        return isset($this->globals[$key]) ? $this->globals[$key] : NULL;
    }
    public function offsetSet($key, $val) {
        echo 'hiii';
        $this->globals[$key] = $val;
    }
    public function offsetUnset($key) {
        unset($this->globals[$key]);
    }
    public function offsetExists($key) {
        return isset($this->globals[$key]);
    }
}

// create a new $GLOBALS array, populated with our new superglobals
$super_globals = array('_SERVER' => new SuperGlobal($_SERVER),
                       '_GET' => new SuperGlobal($_GET),
                       '_POST' => new SuperGlobal($_POST),
                       '_REQUEST' => new SuperGlobal($_REQUEST),
                       // ...
                       );

// overwrite the $GLOBALS array, then extract the new super globals by
// reference into the current scope, overwriting the shorthand to the
// normal superglobals.
$GLOBALS = &new SuperGlobal($super_globals);
extract($super_globals, EXTR_OVERWRITE | EXTR_REFS);

// function to test if the overwriting of the superglobals worked as
// expected
function test_scoping() {
    print_r($GLOBALS);
    print_r($_SERVER);
}

test_scoping();

More to come soon.


Comments

There are no comments, but you look like you have something on your mind.


Comment