php怎么调用父类的方法

PHP
814
2023/11/28 17:10:15
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 如何通过PHP实现WebDAV文件共享