php怎么调用父类的方法

   2025-02-13 4100
核心提示:在PHP中,调用父类的方法有两种方法:使用parent关键字:可以使用parent关键字来调用父类的方法。例如,如果子类继承了父类的方

在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关键字,都可以调用父类的方法。选择哪种方式取决于具体的情况和个人习惯。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言