Jason Lipo
Jason Lipo

Reputation: 761

PHP use class variable in a class array

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?

Upvotes: 3

Views: 111

Answers (3)

BlitZ
BlitZ

Reputation: 12168

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();

Upvotes: 3

Awlad Liton
Awlad Liton

Reputation: 9351

class MyClass {

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

}
$obj = new MyClass();

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212522

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);

Upvotes: 3

Related Questions