gpt4 book ai didi

php - 通过 call_user_func_array 将命名参数传递给 php 函数

转载 作者:行者123 更新时间:2023-12-03 00:26:11 26 4
gpt4 key购买 nike

当尝试使用任意一组参数调用子类中的函数时,我遇到以下问题:

class Base{

function callDerived($method,$params){
call_user_func_array(array($this,$method),$params);
}
}

class Derived extends Base{
function test($foo,$bar){
print "foo=$foo, bar=$bar\n";
}
}

$d = new Derived();
$d->callDerived('test',array('bar'=>'2','foo'=>1));

输出:

foo=2, bar=1

这...并不完全是我想要的 - 除了使用 func_get_args 的索引顺序重新组合数组之外,还有其他方法可以实现此目的吗?是的,当然,我可以简单地传递整个数组并在函数中处理它......但这不是我想要做的。

谢谢

最佳答案

没有。 PHP 不支持命名参数。仅考虑参数的顺序。您可能可以使用 ReflectionClass 将代码本身拆开检查函数参数名称,但最终您仍然需要使用它来重新排序数组。

关于php - 通过 call_user_func_array 将命名参数传递给 php 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6610556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com