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.

4
  • I don't know why you were downvoted. It wasn't me. For the record, your answer was correct: self::${$arr}[] = 'a new element'; Commented Jan 8, 2013 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. Commented Jan 8, 2013 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. Commented Jan 8, 2013 at 22:08
  • Had to wait for the timeout before I could mark it. Commented Jan 8, 2013 at 23:07

1 Answer 1

3

Try this:

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

The curly brackets provide the proper scope to the $

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.