Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a PHP static class property at runtime (dynamically)?

I'd like to do something like this:

public static function createDynamic(){
    $mydynamicvar = 'module'; 
    self::$mydynamicvar = $value;
}

and be able to access the property from within the class with

$value = self::$module;
like image 515
Lucas Batistussi Avatar asked Mar 23 '12 17:03

Lucas Batistussi


1 Answers

I don't know exactly why you would want to do this, but this works. You have to access the dynamic 'variables' like a function because there is no __getStatic() magic method in PHP yet.

class myclass{
    static $myvariablearray = array();

    public static function createDynamic($variable, $value){
        self::$myvariablearray[$variable] = $value;
    }

    public static function __callstatic($name, $arguments){
        return self::$myvariablearray[$name];
    }
}

myclass::createDynamic('module', 'test');
echo myclass::module();
like image 113
AndrewR Avatar answered Sep 20 '22 07:09

AndrewR