在PHP中,可以使用关键字extends来实现继承。通过继承,子类可以继承父类的属性和方法。
以下是一个示例代码,展示了如何在PHP中实现继承:
class ParentClass {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class ChildClass extends ParentClass {
public function __construct($name) {
parent::__construct($name);
}
public function sayHello() {
echo "Hello, " . $this->getName();
}
}
$child = new ChildClass("John");
$child->sayHello(); // 输出:Hello, John
在上面的示例中,ParentClass是父类,ChildClass是子类。子类ChildClass使用关键字extends继承了父类ParentClass。子类通过parent::__construct()方法调用父类的构造函数,从而获取父类的属性name。子类还可以添加自己的方法,例如sayHello()方法。
通过实例化子类对象,可以调用继承自父类的方法,也可以调用子类自己的方法。
上一篇:php判断频繁刷新
下一篇:PHP查询QQ资料
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站