在 PHP 中,子类可以继承父类的构造方法。当子类没有定义自己的构造方法时,会自动继承父类的构造方法。如果子类定义了自己的构造方法,那么父类的构造方法不会被自动继承,但可以通过调用 parent::__construct() 来显式调用父类的构造方法。
以下是一个示例代码:
class ParentClass {
protected $name;
public function __construct($name) {
$this->name = $name;
echo "Parent constructor called with name: " . $this->name . "<br>";
}
}
class ChildClass extends ParentClass {
public function __construct($name) {
parent::__construct($name);
echo "Child constructor called with name: " . $this->name . "<br>";
}
}
$child = new ChildClass("John");
输出结果为:
Parent constructor called with name: John
Child constructor called with name: John
在上面的例子中,ChildClass 继承了 ParentClass 的构造方法,并通过调用 parent::__construct() 显式调用了父类的构造方法。
上一篇:php短连接加密
下一篇:php 调用父类私有变量
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站