如何用PHP中的原始参数调用父类构造函数


How do I call the parent classes constructor with its original parameters in PHP

我有这个代码:

class A {
  var $arr = array();
  function __construct($para) {
    echo 'Not called';
  }
}
class B extends A {
  function __construct() {
    $arr[] = 'new Item';
  }
}

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

现在我可以调用parent::__construct($para),但类B需要知道类A需要的参数。

我更喜欢这个:

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()方法覆盖它一样。

有一种方法可以通过使用call_user_func_array()func_get_args()函数来实现这一点,几乎与您最初描述的完全一样:

class B extends A {
    function __construct() {
        // call the parent constructor with whatever parameters were provided
        call_user_func_array(array('parent', '__construct'), func_get_args());
        // Additional actions that do not need direct access to the parameters
        $arr[] = 'new Item';
    }
}

虽然这是一个有趣的练习,但我个人不建议实际使用它——我认为使用单独的init()方法是一个更好的设计。

一个解决方案是首先不覆盖父构造函数。相反,定义一个单独的(最初为空)init()方法,由父构造函数自动调用。然后可以在子对象中重写该方法,以便执行额外的处理。

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
    }
}