举个例子:
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');
}
}