How to call the constructor with call_user_func_array in PHP(如何在 PHP 中使用 call_user_func_array 调用构造函数)
问题描述
如何使用 call_user_func_array 调用类的构造函数
How could I call the constructor of a class with call_user_func_array
这是不可能的:
$obj = new $class();
call_user_func_array(array($obj, '__construct'), $args);
因为如果构造函数有参数,new 就会失败.
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.
推荐答案
你可以使用 reflection 像:>
You can use reflection like:
$reflect = new ReflectionClass($class);
$instance = $reflect->newInstanceArgs($args);
<小时>
从 PHP 5.6.0 开始,... 运算符也可用于此目的.
As of PHP 5.6.0, the ... operator can also be used for this purpose.
$instance = new $class(...$args);
<小时>
if(version_compare(PHP_VERSION, '5.6.0', '>=')){
$instance = new $class(...$args);
} else {
$reflect = new ReflectionClass($class);
$instance = $reflect->newInstanceArgs($args);
}
这篇关于如何在 PHP 中使用 call_user_func_array 调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 PHP 中使用 call_user_func_array 调用构造函数
基础教程推荐
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
