Reputation: 681
I am trying to build simple config system in php where you can just extend the base and put data in child class and the parent handles everything for you. I will let the code speak for itself. However when i try to do this the child class will not change the parent variable.
Parent class
class ConfigBase {
protected static $data = [];
public static function Get($name)
{
if(!isset(self::$data[$name]))
{
return null;
}
return self::$data[$name];
}
public static function Set($name, $value)
{
self::$data[$name] = $value;
}
}
Child class
class Database extends ConfigBase {
protected static $data = [
'host' => 'localhost',
'username' => 'root',
'password' => '',
'database' => '',
'port' => 3306
];
}
Output:
// NULL
echo Database::Get('host');
Is there a way/workaround/hack to accomplish this?
Upvotes: 4
Views: 2256
Reputation: 316969
Change self
to static
.
When you use self
, it will always evaluate to the class where you defined the assignment. For details, see http://php.net/manual/en/language.oop5.late-static-bindings.php
Or get rid of the static property and use instance variables and methods. Then you are not limited to one configuration of a particular type.
Upvotes: 5