【问题标题】:PHP Constructors: Will an "inherited" constructor use Inherited or Parent class overriden methods?PHP 构造函数:“继承”构造函数会使用继承或父类覆盖方法吗?
【发布时间】:2014-01-31 17:32:49
【问题描述】:

假设我有一堂课

class Item {

public function __construct($id) {
     if(!empty($id)) {
         $this->doSomethingWithID($id);
     }
}

public function dummyMethod() {
    //does Something.
}

protected function doSomethingWithID($id) {
    //Does something with the ID
}

}

如果我有这样的继承类:

class Product extends Item {

 public function __construct() {
      parent::__construct();
 }

 protected function doSomethingWithID($id) {
      //OVERRIDES THE PARENT FUNCTION
 }

}

Product 类会使用被覆盖的 Method 吗?还是会使用 Parent 方法?

【问题讨论】:

  • 你可以试试看
  • 没办法,因为我正在处理别人的代码并且没有找到安全的测试方法,只是想确保它按照我的想法工作,以便我可以继续分析它。谢谢

标签: php inheritance constructor


【解决方案1】:

越具体,它在代码中的优先级就越高。

方法与父母同名的孩子优先。你可以通过说super.method() 来调用父母方法。

【讨论】:

  • 没错。如果子类的构造函数使用了在其类中被覆盖的方法,则不会使用父类的方法。
  • 对不起,我误会你的问题了吗?
  • 不,我给你理由,你说的对,孩子的方法优先。
【解决方案2】:

你已经在继承的类中声明了一个新的构造方法,所以它会使用它,但是当继承的类调用父类的构造方法时,它会使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 2013-06-01
    相关资源
    最近更新 更多