访问在具有该变量的类中实例化的类中的类变量


access class variable within a class being instantiated in class that has the variable

举个例子:

class Parent
{
    public function __construct()
    {
        $this->config = array('a' => 'b');
        $this->child = new Child();
    }
    public function calling()
    {
        $this->config['b'] = 'b';
        $this->child->answering();
    }
}
class Child
{
    public function answering()
    {
        return $this->config['b'];
    }
}

p.s.我知道返回$this->config['b']不起作用,但我不知道如何返回我想要的内容,所以我插入了它作为填充。

如何将Child类实例化为Parent类,并以某种方式访问子类内部的父变量config

使用函数?

class Child
{
   public function foo(&$config) {
      // do stuff with $config
   }
}
class Parent
{
   public function bar() {
      $Child = new Child();
      $Child->foo($this->config);
      echo $this->config; // config should change to whatever Child last set it too
   }
}

例如

class Parent {
    protected function getConfig( $key ){ 
        if ( isset( $this->config[ $key ] ){
            return $this->config[ $key ]; 
        }
        return null;
    }
}
class Child extends Parent {

    public function answering(){
        return $this->getConfig('b');
    }
}