php - 在子 PHP 之后自动调用父构造函数

标签 php oop inheritance constructor parent-child

我尝试使用父类的名称(如构造函数)并为我部分工作。

第一次调用

"DarthVader method"

像构造函数但从不调用

"LukeSkywalker constructor"..

有人知道怎么做吗?

example:

达斯.php

class DarthVader{
    public function DarthVader(){
        echo "-- Obi-Wan never told you what happened to your father.\n";
    }
    public function reponse(){
        echo "-- No. I am your father\n";
    }
}

卢克.php

include("Darth.php")

class LukeSkywalker extends DarthVader{
 public function __constructor(){
        echo "- He told me enough! He told me you killed him!\n"
        $this->response();
    }
}

Expected result:

  • 欧比旺从未告诉过你父亲的遭遇。

  • 他告诉我够多了!他告诉我你杀了他!

  • 没有。我是你爸爸

我真的希望它自动如此。

最佳答案

根据文档:http://php.net/manual/en/language.oop5.decon.php

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).

关于php - 在子 PHP 之后自动调用父构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16469486/

相关文章:

PHP Memcached key 和增加版本号以使缓存无效 - 如何?

php - 使用 PHP 从 MySQL 获取大量数据创建 PDF 文件

c++ - 使数据成员随处可访问,但只读

c# - 类方法返回 `this`是不好的做法吗?

c++ - 继承的构造函数,在 clang++3.9 中编译,在 g++7 中失败

c++ - 类型在编译时已知的虚拟方法

php - Composer 告诉错误的php版本

php - 如何在不中断用户访问的情况下每月刷新大型数据库表

c++ - Ray-AABB 交集函数的类隶属度

c++ - 为什么不能从派生类对象访问父类的赋值运算符