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

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

    A related problem that IS possible (in PHP 5.4.0 and up) is to include various separate groups of static variable or constant declarations and group them together into one class declaration.

    Here is an example:

    trait Added1 // This can be located in one Include file
        {
        static
        $x="hello"; // Can declare more variables here
        }
    trait Added2 // This can be located in another Include file
        {
        static
        $y="world"; // Can declare more variables here
        }
    class G // Global constant and variable declarations class
        {
        use Added1, Added2; // Combines all variable declarations
        }
    
    echo G::$x." ".G::$y; // Shows "hello world" on the web page
    

提交回复
热议问题