Sunday, May 28, 2017

PHP Script: Define Variable Dynamically

PHP Script: Define Variable Dynamically. Its easy:

${"variable"} = "Variable defined dynamically";

echo $variable;


Will output:

Variable defined dynamically

And in class file (both static and instance scope):

SomeClass::test();
SomeClass::test2();

$class = new SomeClass();
$class->test3();

class SomeClass {
    static $xxx = null;

    static function test() {
        self::${"xxx"} = "Value";
    }

    static function test2() {
        echo self::${"xxx"} . "::" . self::$xxx;
    }

    function test3() {
        $this->{"yyyy"} = "Value of YYYY";
        echo "<BR>" . $this->yyyy;
    }
}

No comments:

Post a Comment