PHP:如何将子类__construct()参数传递给parent :: __ construct()? [英] PHP: How to Pass child class __construct() arguments to parent::__construct()?
问题描述
我在PHP中有一个类如下:
I have a class in PHP like so:
class ParentClass {
function __construct($arg) {
// Initialize a/some variable(s) based on $arg
}
}
它有一个子类,如下:
class ChildClass extends ParentClass {
function __construct($arg) {
// Let the parent handle construction.
parent::__construct($arg);
}
}
如果由于某种原因,ParentClass需要更改要采用多个可选参数,我想让我的Child类提供只是为了?除非我重新编码ChildClass,它只会接受构造函数的一个参数,并且只会传递那个参数。
What if, for some reason, the ParentClass needs to change to take more than one optional argument, which I would like my Child class to provide "just in case"? Unless I re-code the ChildClass, it will only ever take the one argument to the constructor, and will only ever pass that one argument.
这是如此罕见或这样一个糟糕的做法,通常的情况是,一个ChildClass不需要继承自一个ParentClass,接受不同的参数?
Is this so rare or such a bad practice that the usual case is that a ChildClass wouldn't need to be inheriting from a ParentClass that takes different arguments?
基本上,我已经在Python中看到,你可以通过 somefunction(* args)将一个可能未知数的参数传递给函数。 code>其中'args'是某种数组/ iterable。 PHP中存在类似的东西吗?或者我应该重构这些类,然后再继续吗?
Essentially, I've seen in Python where you can pass a potentially unknown number of arguments to a function via somefunction(*args)
where 'args' is an array/iterable of some kind. Does something like this exist in PHP? Or should I refactor these classes before proceeding?
推荐答案
在php中有这样的东西,虽然有点冗长:
There is something like this in php, though a bit verbose:
$args = func_get_args();
call_user_func_array(array($this, 'parent::__construct'), $args);
这篇关于PHP:如何将子类__construct()参数传递给parent :: __ construct()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!