PHP:函数参数的名称 [英] PHP: function arguments' names
问题描述
我需要获取匿名函数参数的名称.
I need to get anonymous function arguments' names.
例如:
$func = function ( $param1, $param2 ) { ... };
$names = DO_SOMETHING($func);
// after this $names should become something like array('param1', param2')
从理论上讲,可能是因为var_dump($func)
说$func
是Closure
类的对象,并且具有parameter
属性,即array('param1', 'param2')
.
Theoretically, it is possible because var_dump($func)
says that $func
is the object of Closure
class and have parameter
property which is array('param1', 'param2')
.
php.net上的官方文档没有介绍Closure类的任何方法,这对我有帮助.
Official documentation at php.net describes no methods of Closure class, which can help me.
我尝试直接访问此属性,但是PHP死于致命错误:Closure object cannot have properties
.
I've tried to access this property directly, but PHP died with fatal error: Closure object cannot have properties
.
我试图通过get_object_vars
获取对象变量,但似乎parameter
属性被确定为私有(无论如何,get_object_vars
不会返回它).
I've tried to get object vars by get_object_vars
but it seems the parameter
property is declated as private (anyway, get_object_vars
does not return it).
我唯一知道的一种方法是-截取var_dump
的输出并解析它,但是正如我们容易理解的那样,这不是我们编写脚本的方式=)
The only one way I know -- to intercept the output of var_dump
and parse it, but as we easily understand this is not the way we should write our scripts =)
对不起,我的英语不好.
Sorry for my bad english.
推荐答案
目前无法尝试,但请查看:
Can't try this at the moment, but have a look at:
http://www.php.net/manual/en/class.reflectionfunction.php
尤其是
http://www.php.net/manual/en/reflectionfunctionabstract.getparameters.php
也许这可以解决问题.
试试这个:
$func = function ( $param1, $param2 ) {
/* some code */
};
$refFunc = new ReflectionFunction($func);
foreach ($refFunc->getParameters() as $refParameter) {
echo $refParameter->getName(), '<br />';
}
这篇关于PHP:函数参数的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!