通过call_user_func_array将命名参数传递给php函数 [英] Passing named parameters to a php function through call_user_func_array

查看:135
本文介绍了通过call_user_func_array将命名参数传递给php函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  class Base {

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



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

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

输出:

  foo = 2,bar = 1 

其中...不完全是我想要 - 是否有一种方法可以实现这个超越的重新组合数组,其索引顺序为func_get_args?当然,我可以传递整个数组并在函数中处理它......但这不是我想要做的。

p>

解决方案

没有。 PHP不支持命名参数。只考虑参数的顺序。您可以使用 ReflectionClass 来检查代码本身,以检查函数参数名称,但最终您会发现无论如何都需要使用它来重新排列数组。


When trying to call a function in a child class with an arbitrary set of parameters, I'm having the following problem:

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));

Outputs:

foo=2, bar=1

Which... is not exactly what I wanted - is there a way to achieve this beyond re-composing the array with the index order of func_get_args? And yes, of course, I could simply pass the whole array and deal with it in the function... but that's not what I want to do.

Thanks

解决方案

No. PHP does not support named parameters. Only the order of parameters is taken into account. You could probably take the code itself apart using the ReflectionClass to inspect the function parameter names, but in the end you'd need to use this to reorder the array anyway.

这篇关于通过call_user_func_array将命名参数传递给php函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆