今天遇到一个问题, PHP5.2.x在使用反射做函数包装的时候, 得到”Invocation failed”的异常, 而使用call_user_func代替则不会,
原逻辑太复杂, 经过精简以后可重现异常的代码如下(使用ReflectionFunction为例, ReflectionMethod类似):
- function who(&$name) {
- echo $name;
- }
- $name = "laruence";
- $method = new ReflectionFunction("who");
- $method->invokeArgs(array($name));
- //异常:
- Uncaught exception 'ReflectionException' with message
- 'Invocation of function who() failed'
找原因过程中歧途我就不多言了, 最后跟踪到invokeArgs会调用Zend引擎提供的zend_call_function, 而在zend_call_function中, 有如下一段逻辑引起我的怀疑(注意注释部分):
- int zend_call_function(zend_fcall_info *fci
- , zend_fcall_info_cache *fci_cache TSRMLS_DC) {
- //以上省略
- if (ARG_SHOULD_BE_SENT_BY_REF(EX(function_state).function, i+1)
- && !PZVAL_IS_REF(*fci->params[i])) {
- /*如果形参是引用传递 并且参数不是引用 */
- if ((*fci->params[i])->refcount>1) {
- /*如果参数的refcount大于1 */
- zval *new_zval;
- if (fci->no_separation) {
- /*如果不容许执行分离操作, 则返回失败 */
- return FAILURE;
- }
- //以下省略
也就是说, 如果一个申明为引用传递的参数不为引用传递, 而refcount又大于1, 那么在不容许分离的条件下, 就会导致zend_call_function失败返回(如果对refcount和变量分离不了解, 可以参看我之前的文章深入理解PHP原理之变量分离/引用).
经过验证, 果然invokeArgs在构造zend_fcall_info fci的时候, 是禁止separation的, 所以导致zend_call_funcion返回FAILURE.
而使用call_user_func则不会是因为,call_user_function不考虑no_separation直接分离, 这一点在PHP手册中, call_user_func中是有说明的:
- Note: Note that the parameters for call_user_func() are not passed by reference
找到了原因, 那解决的办法, 也就容易了:
- function who(&$name) {
- echo $name;
- }
- $name = "laruence";
- $method = new ReflectionFunction("who");
- $method->invokeArgs(array(&$name)); //is_ref
#1 by 免费化妆品试用装 on 2010年07月5日 - 07:48
Quote
写得真不错
#2 by 点读机价格 on 2010年07月5日 - 11:14
Quote
楼主,来了看看
恩
恩
很强大
#3 by WP Themes on 2010年07月25日 - 00:08
Quote
Nice post and this mail helped me alot in my college assignement. Say thank you you on your information.