php怎么调用父类的方法
在PHP中,调用父类的方法有两种方法:
- 使用
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()"
- 使用
$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
关键字,都可以调用父类的方法。选择哪种方式取决于具体的情况和个人习惯。
版权声明
本文仅代表作者观点,不代表米安网络立场。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。