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这个方法就可以了。