本文介绍了如何在PHP中使用其原始参数调用父类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

class A {
  var $arr = array();

  function __construct($para) {
    echo 'Not called';
  }
}

class B extends A {
  function __construct() {
    $arr[] = 'new Item';
  }
}

由于B具有自己的A构造函数,构造函数($ para)永远不会被调用.

And as B has its own constructor construct($para) of A never gets called.

现在我可以调用parent :: __ construct($ para),但是类B需要知道类A所需的参数.

Now I could call parent::__construct($para) but then class B would need to be aware of the parameters class A needs.

我希望这样:

class A {
  var $arr = array();

  function __construct($para) {
    echo 'Not called';
  }
}

class B extends A {
  function __construct() {
    parent::__construct(); // With the parameters class B was created.

    // Additional actions that do not need direct access to the parameters
    $arr[] = 'new Item';
  }
}

类似的东西行吗?

我不喜欢这样的事实,所有扩展类A的类都需要定义一个新的构造函数,一旦类A更改了其参数,我想要它们做的就是像类时那样调用类A的构造函数B不会使用自己的__construct()方法覆盖它.

I don't like the fact, that all classes that extend class A would need to define a new constructor, once class A changes its parameters, where all I want them to do is call the constructor of class A like when class B does not overwrite it with an own __construct() method.

推荐答案

一个解决方案是首先不覆盖父构造函数.而是定义一个单独的(初始为空)init()方法,该方法由父构造函数自动调用.然后可以在子级中覆盖该方法,以执行额外的处理.

One solution would be to not override the parent constructor in the first place. Instead, define a separate (initially-empty) init() method that the parent constructor calls automatically. That method could then be overwritten in the child in order to perform the extra processing.

class A {
    public function __construct($para) {
        // parent processing using $para values

        // ..and then run any extra child initialization
        $this->init();
    }
    protected function init() {
    }
}

class B extends A {
    protected function init() {
        // Additional actions that do not need direct access to the parameters
    }
}

这篇关于如何在PHP中使用其原始参数调用父类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 15:27