父类是从子类外部构造的,因此不能从子类内部调用它的构造函数。在这种情况下,应该如何从孩子那里访问父母的属性。
例子:
class MyParent {
protected $args;
protected $child;
public function MyParent($args=false){
$this->args=$args;
$this->child=new MyChild();
}
public function main(){
$this->child->printArgs();
}
}
class MyChild extends MyParent{
public function MyChild(){}
public function printArgs(){
Echo "args: ".$this->args['key']." = ".$this->args['value']."\n";
}
}
$parent=new MyParent(array('key'=>'value'));
$parent->main();
运行时返回空变量:
jgalley@jgalley-debian:~/code/otest$ php run.php
args: =