【发布时间】:2013-06-04 10:38:44
【问题描述】:
谁能解释一下为什么这段代码有效?
<?php
class iParent
{
private $device;
private $browser;
public function __construct()
{
$this->device = 'iPad';
$this->browser = 'Safari';
}
public function getDetails()
{
return 'Device ' . $this->device . ' ' . 'Browser ' . $this->browser;
}
}
/**
*
*/
class iParentChild extends iParent
{
public function __construct()
{
echo 'IParentChild constructor';
}
public function display()
{
return $this->getDetails();
}
}
$obj = new iParentChild;
echo $obj->display();
// Output
Device iPad Browser Safari
我认为只有在iParentChild 的构造函数中调用parent::__construct()(初始化父构造函数)才能工作。
//更新 我在 iParentChild 中添加了 __construct
【问题讨论】:
-
究竟有什么困惑?您没有指定
iParentChild构造函数,因此它继承了父类的构造函数。就这么简单。
标签: php class oop constructor parent