Reputation: 1129
Is it possible to change the default value of a static class property inside the constructor in php?
class Test {
public static $property = 'default';
public function __construct() {
self::$property = 'new value';
}
}
The code above doesn't do that. Thanks in advance!
EDITS
I know I can change the value outside the class
Test::$property = 'new value';
echo Test::$property;
I was wondering if I could do it inside class constructor.
Upvotes: 2
Views: 2127
Reputation: 2405
With PHP 5.3, you can use the late static binding.
Replace "self" by "static" in your code :
class Test {
public static $property = 'default';
public function __construct() {
static::$property = 'new value';
}
}
It will works ;)
Upvotes: 2
Reputation: 3682
This is working for me.
class Test {
public static $property = 'default';
public function __construct() {
echo self::$property = 'new value'; // for EXample echo val of property
}
}
//When create a new object of class it shows / Assigns value of static property
$test = new Test();
echo Test::$property;
Upvotes: 0