温馨提示×

php怎么调用父类的方法

PHP
小亿
193
2023-12-04 17:10:15
栏目: 编程语言

在PHP中,调用父类的方法有两种方法:

  1. 使用parent关键字: 可以使用parent关键字来调用父类的方法。例如,如果子类继承了父类的方法foo(),可以使用parent::foo()来调用父类的foo()方法。
class ParentClass { protected function foo() { echo "ParentClass foo()"; } } class ChildClass extends ParentClass { public function foo() { parent::foo(); // 调用父类的foo()方法 echo "ChildClass foo()"; } } $child = new ChildClass(); $child->foo(); // 输出:"ParentClass foo() ChildClass foo()" 
  1. 使用$this关键字: 在子类中,可以使用$this关键字来调用父类的方法。例如,如果子类继承了父类的方法foo(),可以使用$this->foo()来调用父类的foo()方法。
class ParentClass { protected function foo() { echo "ParentClass foo()"; } } class ChildClass extends ParentClass { public function foo() { $this->foo(); // 调用父类的foo()方法 echo "ChildClass foo()"; } } $child = new ChildClass(); $child->foo(); // 输出:"ParentClass foo() ChildClass foo()" 

无论使用parent关键字还是$this关键字,都可以调用父类的方法。选择哪种方式取决于具体的情况和个人习惯。

0