我是OOP PHP的初学者。我有这样的代码
class Index
{
public $activepage = true;
public $url;
public $page;
function __construct()
{
if ($this->activepage) {
$this->url = "Yes";
$this->page = "Home";
} else {
$this->url = "No";
$this->page = "Index";
}
}
public function show()
{
return $this->page;
}
public function showTest()
{
return "test";
}
}
class Home extends Index
{
function __construct()
{
echo $this->show();
}
}
$page = new Home;
我的问题是: 为什么我在调用Home类时有空白页?
但是当我在Home类中改变构造函数时,就像这个echo $this->showTest();
一样,它可以工作。并显示" test"在屏幕上。
我在index类中的show方法和showTest方法之间实际上有什么不同?
答案 0 :(得分:2)
在__construct()
类中添加Home
时,它会覆盖父类Index
中的构造。
您可以使用以下方法手动调用父构造
function __construct()
{
parent::__construct();
echo $this->show();
}
答案 1 :(得分:0)
您可以调用类类的父类方法
parent::show()