php – Creating static properties dynamically (in the constructor)

Question:

Please tell me how best to implement this It is necessary that the created properties are static.

class Config
{
    public function __construct()
    {
        $json = json_decode(file_get_contents('config.json'), true);
        foreach($json as $k=>$v){
            $this->$k = $v;
        }
    }
}

Answer:

You cannot define static properties of a class dynamically. You can dynamically call an existing property using self::$k and static::$k . However, it is impossible to create a new static property in an object, the actual static variable is at the class level.

As I understand it, you want to create a dictionary with configuration settings? Then it is better to create one static variable-array and store data in it, or even better to implement the ArrayAccess interface and use the resulting object as an array (prohibiting making changes to it).

Scroll to Top