如何在PHP中使用call_user_func_array调用构造函数 [英] How to call the constructor with call_user_func_array in PHP
本文介绍了如何在PHP中使用call_user_func_array调用构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用call_user_func_array来调用类的构造函数
这是不可能的:
$ obj = new $ class();
call_user_func_array(array($ obj,'__construct'),$ args);
因为如果构造函数有参数,则 new p>
约束:我不控制我要实例化的类,也不能修改它们。
解决方案
你可以使用反射 like:
$ reflect = new ReflectionClass($ class);
$ instance = $ reflect-> newInstanceArgs($ args);
自PHP 5.6.0起, ...
运算符也可用于此目的。
$ instance = new $ class ... $ args);
if (version_compare(phpversion(),'5.6.0','> =')){
$ instance = new $ class(eval('...')。
} else {
$ reflect = new ReflectionClass($ class);
$ instance = $ reflect-> newInstanceArgs($ args);
}
How could I call the constructor of a class with call_user_func_array
It is not possible to do :
$obj = new $class();
call_user_func_array(array($obj, '__construct'), $args);
because if the constructor has parameters, the new will fail.
Constraint : I do not control the classes that I have to instantiate, nor can I modify them.
Don't ask me why I want to do this crazy thing, this is a crazy test.
解决方案
You can use reflection like:
$reflect = new ReflectionClass($class);
$instance = $reflect->newInstanceArgs($args);
As of PHP 5.6.0, the ...
operator can also be used for this purpose.
$instance = new $class(...$args);
if(version_compare(phpversion(), '5.6.0', '>=')){
$instance = new $class(eval('...') . $args);
} else {
$reflect = new ReflectionClass($class);
$instance = $reflect->newInstanceArgs($args);
}
这篇关于如何在PHP中使用call_user_func_array调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文