简体   繁体   中英

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. 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM