Maison  >  Article  >  développement back-end  >  php 利用反射执行callable

php 利用反射执行callable

WBOY
WBOYoriginal
2016-06-06 20:37:241100parcourir

现在有一个这样的函数

<code><?php $func = function($a,$b){
  ......
}
?>
</code>

我想利用反射,再用call_user_func执行,
当然,我不是白痴和多此一举,主要是因为上面的$func是一个数组中的值,我现在要写一个解析数据函数,会遇到$func,
写法如下:

<code>$ReflectionFunction = new \ReflectionFunction($func);
foreach ($ReflectionFunction->getParameters() as $param) {
                    $params[] = $param->getName();
                }
                print_r($params);exit();
</code>

但这个只能获取,函数参数的名称,却无法使用

<code>call_user_func(..,array(param1,param2))
</code>

所以想请教下各位,怎么才能使这个传入的参数有效呢?

回复内容:

现在有一个这样的函数

<code><?php $func = function($a,$b){
  ......
}
?>
</code>

我想利用反射,再用call_user_func执行,
当然,我不是白痴和多此一举,主要是因为上面的$func是一个数组中的值,我现在要写一个解析数据函数,会遇到$func,
写法如下:

<code>$ReflectionFunction = new \ReflectionFunction($func);
foreach ($ReflectionFunction->getParameters() as $param) {
                    $params[] = $param->getName();
                }
                print_r($params);exit();
</code>

但这个只能获取,函数参数的名称,却无法使用

<code>call_user_func(..,array(param1,param2))
</code>

所以想请教下各位,怎么才能使这个传入的参数有效呢?

我感觉你想做的事情就是用
感觉可能是你使用的Php版本太老了,5.6开始,
可以这么做了,前提是你的$func要是个数组
functionA(...$func)
PS:functionA是你想call_user_func的函数

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn