温馨提示×

使用PHP parent调用父类方法的技巧

PHP
小樊
82
2024-07-31 15:14:10
栏目: 编程语言

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

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

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

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

在上面的示例中,ChildClass继承了ParentClass,并重写了sayHello方法。在ChildClass中的sayHello方法中,使用parent::sayHello()调用了父类的sayHello方法。这样就能够在子类中调用父类的方法了。

0