如何在 PHP 中调用子类中的父类构造函数?
object oriented programmingphpprogramming更新于 2025/4/29 18:52:17
在子类中调用父类构造函数方法时,我们将面临两种情况。
情况 1
如果子类定义了构造函数,我们不能在子类中直接运行父类构造函数。为了运行父类构造函数,需要在子类构造函数中调用 parent::__construct()。
示例
<?php
class grandpa{
public function __construct(){
echo "I am in Tutorials Point"."
";
}
}
class papa extends grandpa{
public function __construct(){
parent::__construct();
echo "I am not in Tutorials Point";
}
}
$obj = new papa();
?>
Output: I am in Tutorials Point I am not in Tutorials Point
解释
在上面的例子中,我们使用了 parent::__construct() 来调用父类构造函数。
案例2
如果子类没有定义构造函数,那么它可以像普通类方法一样从父类继承(如果它没有被声明为私有的)。
示例
<?php
class grandpa{
public function __construct(){
echo "I am in Tutorials point";
}
}
class papa extends grandpa{
}
$obj = new papa();
?>
输出
I am in Tutorials Point
解释
这里隐式调用父类,因为在子类中我们没有在子类中声明任何构造函数。

