php父类调用子类方法
时间: 2023-08-04 20:14:37 浏览: 42
在 PHP 中,父类可以通过使用 `parent` 关键字来调用子类中重写的方法。具体实现方式如下:
```
class ParentClass {
public function test() {
echo "ParentClass";
}
}
class ChildClass extends ParentClass {
public function test() {
echo "ChildClass";
}
public function runTest() {
parent::test(); // 调用父类方法
$this->test(); // 调用子类方法
}
}
$child = new ChildClass();
$child->runTest(); // 输出 "ParentClass ChildClass"
```
在子类中,使用 `parent::methodName()` 来调用父类中的方法。在上述示例中,`ChildClass` 中的 `runTest()` 方法中调用了 `ParentClass` 中的 `test()` 方法,同时也调用了 `ChildClass` 中重写的 `test()` 方法。
相关问题
php子类重写父类的方法
当一个子类继承了一个父类时,它可以使用父类的方法。有时候,子类需要修改或者重写父类的方法,以满足子类的需求。在 PHP 中,子类可以通过重写父类的方法来实现这一点。以下是一个示例:
```php
class ParentClass {
public function myMethod() {
echo "This is from the parent class.";
}
}
class ChildClass extends ParentClass {
public function myMethod() {
echo "This is from the child class.";
}
}
// 创建子类对象
$childObj = new ChildClass();
// 调用子类的方法
$childObj->myMethod(); // 输出 "This is from the child class."
```
在上面的示例中,子类 `ChildClass` 继承了父类 `ParentClass` 的方法 `myMethod()`。然后,子类重写了 `myMethod()` 方法,并且在方法中输出了不同的字符串。当我们调用子类对象的 `myMethod()` 方法时,它会输出子类中重写的字符串。
PHP子类会调用父类的构造函数吗
在 PHP 中,子类默认会调用父类的构造函数。如果子类没有定义构造函数,那么会自动调用父类的构造函数。如果子类定义了构造函数并且需要调用父类的构造函数,则可以使用 `parent::__construct()` 来实现。例如:
```
class ParentClass {
public function __construct() {
echo "Parent constructor called";
}
}
class ChildClass extends ParentClass {
public function __construct() {
parent::__construct();
echo "Child constructor called";
}
}
$obj = new ChildClass();
```
在上面的例子中,当实例化 `ChildClass` 类时,它会先调用父类的构造函数,然后再调用子类的构造函数。输出结果为:
```
Parent constructor called
Child constructor called
```