PHP:函数参数的名称 [英] PHP: function arguments' names

查看:32
本文介绍了PHP:函数参数的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取匿名函数参数的名称.

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)$funcClosure 类的对象并且有 参数 属性,即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 =)

抱歉我的英语不好.

推荐答案

暂时无法尝试,请查看:

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屋!

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