1

I'm refreshing my PHP knowledge and have a problem I can't solve on my own:

I have a class with two private static arrays that I want to store as values of a further (multideimensional) static class array but I always get a *unexpected T_VARIABLE* error. Here is my simplyfied sample code (just with one instead of two static arrays to fill in the following multidimensional array) that fails:

class MyClass {
  private static $firstArr = array('a' => 'A', 'b' => 'B');

  private static $multiArr = array('a' => self::$firstArr);
}

I really don't understand what's wrong here. I could easily replace the self::$firstArr with the array declaration of $firstArr itself, but I'd love to understand what I'm doing wrong here, anyway.

So any comment is welcome!

Cheers, Roman.

1 Answer 1

3

You can't do any kind of extra evaluation when declaring class properties.

private static $multiArr = array('a' => self::$firstArr);
//                Can't do this    -----^

Link in docs

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

You're right to avoid copy/paste - This sort of 'run-time information' is usually done in the constructor.

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

2 Comments

I see, sounds fair. Thank you for your explanation, I didn't know that yet (and it probably means that what I'm doing should better be done in a different way...).
Yes it's a bit annoying, when you need to evaluate expressions from static properties you need to place those in a static init method that you call from the class file itself for example, or find another design.. @Mike B how do you manage that practically?

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.