ReflectionClass::newInstance 在调用构造函数中含有引用参数的时候报错的解决方法...

class a {
     public function __construct(&$a, $c) {
     }
}

// this works
$A = new stdClass();
$a = new a($A, 11);

// also this works
$classname = "a";
$a = new $classname($A, 10);

// but this fails:
$r = new ReflectionClass("a");
$r->newInstance($A, 10);

运行以上代码就不报如下错误...

PHP Warning:  Parameter 1 to a::__construct() expected to be a reference, value given in reflection.php on line 15

PHP Warning:  ReflectionClass::newInstance(): Invocation of a's constructor failed in reflection.php on line 15

这是在官方文档中该方法文档中的一个note,但是这个note被vote down 5次,对此我就很好奇。为什么会这样呢?

经过一轮验证后,其实发现很简单。其实文档已经说出原因:

args

Accepts a variable number of arguments which are passed to the class constructor, much like call_user_func().

就是这个提示,说如果传输任意数量参数给构造函数的时候,这个时候就类似call_user_func()。

打开call_user_func()的文档一开就会得到警告:

Note:

请注意,传入call_user_func()的参数不能为引用传递。

就是这样,这个方法是不允许调用带有引用的参数的构造函数。

那么我们真的需要用反射来调用带有引用参数的构造函数的时候,只需要调用ReflectionClass::newInstanceArgs这个方法就可以了。

 

转载于:https://my.oschina.net/zerodeng/blog/879503

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值