Heim  >  Artikel  >  Backend-Entwicklung  >  php 利用反射执行callable

php 利用反射执行callable

WBOY
WBOYOriginal
2016-06-06 20:37:241100Durchsuche

现在有一个这样的函数

<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的函数

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn