我有这个代码:
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()
方法是一个更好的设计。
关于php - 如何在 PHP 中使用其原始参数调用父类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17826958/