在PHP中实现继承,需要使用关键字"extends"。首先,定义一个父类,在类的前面加上"class"关键字,紧接着加上类名,然后在花括号中定义属性和方法。
例如:
class ParentClass {
public $property1;
protected $property2;
private $property3;
public function method1() {
// some code here
}
protected function method2() {
// some code here
}
private function method3() {
// some code here
}
}
然后,定义子类,在子类名后紧跟extends关键字和父类名。然后,再次使用花括号来定义子类的属性和方法。
例如:
class ChildClass extends ParentClass {
// some code here
}
在子类中,可以直接使用父类的属性和方法。如果想要调用父类的方法,可以使用"parent::"关键字。
例如:
class ChildClass extends ParentClass {
public function newMethod() {
parent::method1();
// some code here
}
}
以上是在PHP中实现继承的基本方法。如果需要更详细的教程和示例代码,可以参考PHP官方文档或者其他在线教程。