php调用父类的构造函数

在 PHP 中,一个子类继承自父类时,可以通过使用 `parent::__construct()` 调用父类的构造函数。构造函数是一个特殊的方法,它会在创建对象时自动调用,并且用于初始化对象的属性和执行一些必要的操作。构造函数的调用顺序是从父类开始,然后依次调用子类的构造函数。

当我们创建一个子类时,可以选择是否定义自己的构造函数。如果没有定义构造函数,子类会自动继承父类的构造函数。如果子类定义了自己的构造函数,那么默认情况下它会覆盖父类的构造函数。但是,如果我们想在子类的构造函数中调用父类的构造函数,可以使用 `parent::__construct()`。

下面是一个示例,演示了如何调用父类的构造函数:

```php

class ParentClass {

protected $name;

public function __construct($name) {

$this->name = $name;

}

public function getName() {

return $this->name;

}

}

class ChildClass extends ParentClass {

protected $age;

public function __construct($name, $age) {

parent::__construct($name);

$this->age = $age;

}

public function getAge() {

return $this->age;

}

}

$child = new ChildClass("John", 25);

echo $child->getName(); // 输出 "John"

echo $child->getAge(); // 输出 25

```

在上面的例子中,`ParentClass` 是父类,拥有一个构造函数 `__construct` 和一个公共方法 `getName`。`ChildClass` 是子类,继承自 `ParentClass`,拥有一个构造函数 `__construct` 和一个公共方法 `getAge`。

在子类的构造函数中,我们首先使用 `parent::__construct($name)` 调用父类的构造函数,并传递参数 `$name` 给父类的构造函数。然后,我们在子类的构造函数中初始化子类特有的属性 `$age`。

在调用 `$child->getName()` 时,会调用父类的 `getName` 方法,返回父类中的属性 `$name` 的值 "John"。调用 `$child->getAge()` 时,会返回子类中的属性 `$age` 的值 25。

除了在构造函数中调用父类的构造函数外,我们还可以在子类的其他方法中调用父类的方法。这可以通过使用 `parent::methodName()` 语法来实现。下面是一个示例:

```php

class ParentClass {

protected $name;

public function __construct($name) {

$this->name = $name;

}

public function getName() {

return $this->name;

}

protected function printName() {

echo $this->getName();

}

}

class ChildClass extends ParentClass {

public function printParentName() {

parent::printName();

}

}

$child = new ChildClass("John");

$child->printParentName(); // 输出 "John"

```

在上面的示例中,父类 `ParentClass` 中有一个受保护的方法 `printName`,用于打印父类的名称。子类 `ChildClass` 中有一个公共方法 `printParentName`,用于调用父类的 `printName` 方法。

在子类的方法 `printParentName` 中,我们使用 `parent::printName()` 调用父类的 `printName` 方法。在调用 `$child->printParentName()` 时,会输出父类中的属性 `$name` 的值 "John"。

综上所述,PHP 中可以通过使用 `parent::__construct()` 在子类的构造函数中调用父类的构造函数。同样,通过使用 `parent::methodName()` 可以在子类的方法中调用父类的方法。这样,可以有效地重用父类的功能,并在子类中扩展或覆盖其行为。 如果你喜欢我们三七知识分享网站的文章, 欢迎您分享或收藏知识分享网站文章 欢迎您到我们的网站逛逛喔!https://www.37seo.cn/

点赞(55) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿
发表
评论
返回
顶部