Reputation: 761
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
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
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
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