如何使用具有未定义参数数量的回调函数?
我认为一个例子可能更好:
我在课堂上有两个功能,它们非常相似,但有几行。我想要做的是使用公共代码调用函数并使用特定代码传递回调。我在使用不同对象时使用模板方法模式来执行此操作,但现在情况并非如此。
一些虚拟代码:
public function firstMethod($commonParam, $particularParam)
{
//some common staff
if ($whatever) {
//more common staff
//do something particular with $particularParam
}
return $something
}
public function secondMethod($commonParam, $particularParam1, $particularParam2)
{
//some common staff
if ($whatever) {
//more common staff
//do something particular with $particularParam1 and particularParam2
}
return $something
}
现在我想要这样的事情:
public function firstMethod($commonParam, $particularParam)
{
$lamba = function ($particularParam){
//do something particular with $particularParam
};
return $this->commonMethod($commonParam, $lambda);
}
public function secondMethod($commonParam, $particularParam1, $particularParam2)
{
$lamba = function ($particularParam1, $particularParam2){
//do something particular with $particularParam1 and $particularParam2
};
return $this->commonMethod($commonParam, $lambda);
}
private function commonMethod($commonParam, $callback)
{
//some common staff
if ($whatever) {
//more common staff
//CALLING $callback. But how can a pass the parameters when it is not the same number for the anonymous functions?
}
return $something
}
谢谢。
答案 0 :(得分:0)
这取决于您开发应用程序的PHP版本。在PHP 5.6.x中,涉及到一个启动操作符。所以你可以按如下方式使用它:
function bla($foo, ...$params) {
// $params will be an array with all your parameters
}
在旧版本的PHP中,您将获得与func_get_args()
相同的结果function bla() {
$numOfArgs = func_num_args();
$parameters = func_get_args();
return $something;
}
// call
$result = bla($param1, $param2, $param3, $param4);