Question

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.

Was it helpful?

Solution

Try this:

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

The curly brackets provide the proper scope to the $

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top