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

前端 未结 4 1897
遥遥无期
遥遥无期 2021-02-19 12:47

I\'d like to do something like this:

public static function createDynamic(){
    $mydynamicvar = \'module\'; 
    self::$mydynamicvar = $value;
}
4条回答
  •  情歌与酒
    2021-02-19 13:37

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

提交回复
热议问题