0

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.

Community
  • 1
  • 1
Greg
  • 12,119
  • 5
  • 32
  • 34
  • I don't know why you were downvoted. It wasn't me. For the record, your answer was correct: self::${$arr}[] = 'a new element'; – Greg Jan 08 '13 at 22:04
  • No I meant, why did your question get downvoted? I don't feel it should have. Anyway I added my answer as an actual answer, below. – Madbreaks Jan 08 '13 at 22:05
  • You bet. Since you indicated my answer was correct please mark it as such by clicking the checkbox next to the up/down vote counter. – Madbreaks Jan 08 '13 at 22:08
  • Had to wait for the timeout before I could mark it. – Greg Jan 08 '13 at 23:07

1 Answers1

3

Try this:

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

The curly brackets provide the proper scope to the $

Madbreaks
  • 19,094
  • 7
  • 58
  • 72