[英]How to use default parameter value in a nested call?
I have this situation: function a
(a class method, but it's not important, here...) invokes function b
. 我
a
这种情况:函数a
(一个类方法,但这并不重要,在这里...)调用函数b
。
Function a
has one parameter (say, $p2
), with a default value. 函数
a
具有一个参数(例如$p2
),具有默认值。
Function b
has one parameter (say, $q2
), with a default value, too. 函数
b
具有一个参数(例如$q2
),也具有默认值。
If function a
is called without the parameter $p2
, function b
should be called without the parameter $q2
, too, to force it using it's default value. 如果
a
不带参数$p2
情况下调用函数b
应在不带参数$q2
的情况下调用函数b
,以强制使用其默认值。
If function a
is called with the parameter $p2
, function b
should be called with the parameter $q2
. 如果函数
a
被调用 ,参数$p2
,函数b
应与参数调用$q2
。
To clearify with an example: 要举例说明:
function a($p1, $p2 = "default value one") {
if ($p2 === "default value") {
b($p1);
} else {
b($p1, $p2);
}
}
function b(q1, q2 = "default value two") {
...
}
Of course it's possible to use a test, as in the example above, but it looks me a really ugly solution... The question is: 当然,可以像上面的示例中那样使用测试,但是看起来我是一个非常丑陋的解决方案...问题是:
Is there a better (faster, cleaner, smarter) code to implement this use case? 是否有更好(更快,更干净,更智能)的代码来实现此用例?
I think something like this should be what you're looking for: 我认为您需要的是这样的东西:
Just get all function arguments with func_get_args()
, then simply call your next function with call_user_func_array()
. 只需使用
func_get_args()
获取所有函数参数,然后只需使用call_user_func_array()
调用下一个函数即可。
function a($p1, $p2 = "default value") {
call_user_func_array("b", func_get_args());
}
Function a
default parameter must have same value as function b
default parameter: 功能
a
默认的参数必须具有相同的值,函数b
默认参数:
function a($p1, $p2 = null) {
b($p1, $p2);
}
function b($p1, $p2 = null) {
var_dump($p1, $p2);
}
So calling a
with both parameters will pass these parameters to function b
, while calling function a
with only first parameter set will call b
with passed first from user and second parameter as default value: 因此,调用
a
与这两个参数将这些参数传递给函数b
,而调用函数a
只有第一组参数将调用b
从用户和默认值第二个参数中率先通过了:
a(2, 5);
a(2,5); // --> (int)2 (int)5
//->(int)2(int)5
a(2);
a2); // --> (int)2 NULL
//->(int)2 NULL
[UPDATE] [UPDATE]
If functions can have different default values, than you need to detect default value: 如果函数可以具有不同的默认值,则您需要检测默认值:
function a($p1, $p2 = null) {
$p2 = !is_null($p2) ? $p2 : 'defaultB';
b($p1, $p2); // For string use `stricmp($p2, 'defaultA') !== 0`
}
function b($p1, $p2 = 'defaultB');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.