如何在PHP中使用其原始参数调用父类构造函数

Joc*_*ung 5 php oop inheritance

我有这个代码:

class A {
  var $arr = array();

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

class B extends A {
  function __construct() {
    $arr[] = 'new Item';
  }
}
Run Code Online (Sandbox Code Playgroud)

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

现在我可以调用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';
  }
}
Run Code Online (Sandbox Code Playgroud)

会有类似的东西吗?

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

jcs*_*nyi 6

通过使用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';
    }
}
Run Code Online (Sandbox Code Playgroud)

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


jcs*_*nyi 5

一个解决方案是首先不覆盖父构造函数。相反,定义一个单独的(初始为空的)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
    }
}
Run Code Online (Sandbox Code Playgroud)