Sophivorus
Sophivorus

Reputation: 3083

Static variable variables in php 5.2

I'm trying to define the following function:

function set($key, $value, $default = null)
    {
    if ($value)
        static $$key = $value;
    else
        static $$key = $default;
    }

But when I call it, I get the error "Parse error: syntax error, unexpected '$', expecting T_VARIABLE". I guess there is a problem with defining static variable variables, but I can't find a workaround. Can you? Thanks!

Upvotes: 0

Views: 1204

Answers (2)

rid
rid

Reputation: 63600

If I really wanted to do something like that, I'd use a static array instead:

function set($key, $value, $default = null)
{
    static $values = array();
    $values[$key] = is_null($value) ? $default : $value;
}

If you want to also be able to access this data, a better idea is to encapsulate it in a class.

class Registry
{
    private static $values = array();

    public static function set($key, $value, $default = null)
    {
        self::$values[$key] = is_null($value) ? $default : $value;
    }

    public static function get($key, $default = null)
    {
        return array_key_exists($key, self::$values) ? self::$values[$key] : $default;
    }
}

Then you can use the class statically:

Registry::set('key', 'value', 'default');
$value = Registry::get('key', 'default');

An even better way of doing this is to not use the static keyword at all, and instead make a normal class with normal properties, then make a single instance of it and use that instance.

class Registry
{
    private $values = array();

    public function set($key, $value, $default = null)
    {
        $this->values[$key] = is_null($value) ? $default : $value;
    }

    public function get($key, $default = null)
    {
        return array_key_exists($key, $this->values) ? $this->values[$key] : $default;
    }
}

You can then make an instance of the class and pass it along:

$registry = new Registry();
do_something_that_requires_the_registry($registry);

Upvotes: 1

Jan Dragsbaek
Jan Dragsbaek

Reputation: 8101

if you are doing this in a class, you can use the __get and __set magic functions.

I use it like this in my projects:

class foo
{

    public function __set($key, $value)
    {
        $this->vals[$key] = $value;
    }

    public function __get($key)
    {
        return $this->vals[$key];
    }
}

$foo = new foo();
$foo->bar = "test";
echo $foo->bar;

Upvotes: 1

Related Questions