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

前端 未结 4 1907
遥遥无期
遥遥无期 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:28

    Static properties must be defined in the class definition. Therefore, real static properties cannot be created dynamically like regular properties.

    For example, if you run this:

    ...you'll get this error

    Fatal error: Access to undeclared static property: MyClass::$mydynamicvar test.php on line 8
    

    Notice how the error occurs on line 8 when trying to set the property instead of line 14 or 15 (as you might expect if you were simply doing it wrong and dynamically creating static properties was actually possible).

提交回复
热议问题