Frage

Similar to this question Dynamically call a static variable (array) , but for writing to the variables.

I'm trying to initialize a couple static arrays in my constructor, but can't figure out how to code their names dynamically.

When I try this:

class MyClass {
    public static $something1 = array();
    public static $something2 = array();

    function __construct() {
        for( $i = 1; $i <= 2; $i++ ){
            $arr = "something{$dynamic}";
            self::$$arr[] = "a new element";
        }
    }
}

I get this error even if I don't call the constructor:

Fatal error: Cannot use [] for reading

Is there any way to accomplish this without using eval? I'm using PHP 5.4.

War es hilfreich?

Lösung

Try this:

self::${$arr}[] = 'a new element';

The curly brackets provide the proper scope to the $

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top