[英]Change parent variable from child class
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. 我正在尝试在php中构建简单的配置系统,您可以在其中扩展基础并将数据放在子类中,而父类则为您处理所有事情。 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? 有没有一种方法/解决方法/ hack来完成此任务?
Change self
to static
. 将self
更改为static
。
When you use self
, it will always evaluate to the class where you defined the assignment. 当您使用self
,它将始终评估为您定义分配的类。 For details, see http://php.net/manual/en/language.oop5.late-static-bindings.php 有关详细信息,请参见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. 这样,您就不仅限于特定类型的一种配置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.