3

I am trying to use a variable in an array within my class

class MyClass {

public static $a = "World";

public static $b = array("Hello" => self::$a);

}

This code doesn't work. Should I be using MyClass::$a or something else. Any ideas?

6
  • 4
    Class properties can't contain expressions that have to be evaluated at runtime, and self::$a requires a runtime evaluation. If your $a isn't going to change, make it a constant Commented Dec 29, 2013 at 12:14
  • Initialize $b in the class constructor. Commented Dec 29, 2013 at 12:16
  • @Barmar, slightly awkward to initialize in the constructor as it's static Commented Dec 29, 2013 at 12:17
  • 1
    Only slightly. if (!$b) { self::$b = array(...) }. Commented Dec 29, 2013 at 12:20
  • @Barmar - but that means instantiating the class, which shouldn't be a prerequisite for anything defined as static Commented Dec 29, 2013 at 12:22

3 Answers 3

3

You probably can instatiate them at runtime:

class MyClass {
    public static $a;
    public static $b;
}

MyClass::$a = "World";
MyClass::$b = [ "Hello" => MyClass::$a ];

Or you can create a static initialization method:

class MyClass {
    public static $a;
    public static $b;

    public static function init(){
        static::$a = "World";
        static::$b = [ "Hello" => static::$a ];
    }
}

MyClass::init();
Sign up to request clarification or add additional context in comments.

1 Comment

This is very good. It works on what @awlad-liton said, but this approach is more useful - thanks a lot!
3

If your $a won't change, make it a constant

class MyClass {

    const a = "World";

    public static $b = array("Hello" => self::a);

}

var_dump(MyClass::$b);

2 Comments

Yes, this does work. However in the context I want to use it, I don't want $a to be a constant.
In that case, if your properties still need to be static, @HAL9000 has provided your options.
1
class MyClass {

    public static $a = "World";
    public static $b;
    public function __construct(){
      self::$b = array("Hello" => self::$a);
    }

}
$obj = new MyClass();

4 Comments

Yes I think that's the answer. I have to use a __construct function. Thanks a lot!
Note that if you want $b to automatically reflect any changes made to $a, you'll need to set self::$a by reference
@Jason Lipo: You accepted my answer and after that someone edited his answer after acceptance you did change your acceptance also!!
I changed the acceptance not because of the edit. I tried the static function approach from @HAL9000 and that proved to work the most simply.

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.