【发布时间】:2013-07-25 15:03:21
【问题描述】:
class parents{
public $a;
function __construct(){
echo $this->a;
}
}
class child extends parents{
function __construct(){
$this->a = 1;
parent::__construct();
}
}
$new = new child();//print 1
上面这段代码打印1,这意味着每当我们创建一个子类的实例,并为从其父类继承的属性赋值时,其父类中的属性也已被赋值。但下面的代码显示不同:
class parents{
public $a;
function test(){
$child = new child();
echo $this->a;
}
}
class child extends parents{
function __construct(){
$this->a = 1;
}
}
$new = new parents();
$new->test();//print nothing
我给它的子类赋值,而父类显然没有赋值给它的子类的值,为什么?
谢谢!
【问题讨论】:
标签: php constructor inheritance