温馨提示×

PHP construct函数调用父类的方法

PHP
小樊
86
2024-07-23 01:59:58
栏目: 编程语言

在PHP中,可以使用parent::关键字来调用父类的方法。以下是一个例子:

class ParentClass {
    public function sayHello() {
        echo "Hello from ParentClass!";
    }
}

class ChildClass extends ParentClass {
    public function sayHello() {
        parent::sayHello(); // 调用父类的方法
        echo "Hello from ChildClass!";
    }
}

$child = new ChildClass();
$child->sayHello();

在上面的例子中,ChildClass继承自ParentClass,在ChildClass中重写了sayHello方法,并在重写方法中使用parent::sayHello()来调用父类的方法。当调用sayHello方法时,会先输出"Hello from ParentClass!“,然后再输出"Hello from ChildClass!”。

0