【问题标题】:How to call the constructor with call_user_func_array in PHP如何在 PHP 中使用 call_user_func_array 调用构造函数
【发布时间】:2010-03-09 13:18:01
【问题描述】:

如何使用 call_user_func_array 调用类的构造函数

这是不可能的:

$obj = new $class();
call_user_func_array(array($obj, '__construct'), $args); 

因为如果构造函数有参数,new会失败。

约束:我不控制必须实例化的类,也不能修改它们。

不要问我为什么要做这种疯狂的事情,这是一个疯狂的测试。

【问题讨论】:

标签: php constructor


【解决方案1】:

您可以使用reflection 喜欢:

$reflect  = new ReflectionClass($class);
$instance = $reflect->newInstanceArgs($args);

从 PHP 5.6.0 开始,... operator 也可用于此目的。

$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);
}

【讨论】:

  • 这个...语法太强大了:D
  • 这三个点拯救了我的一天。谢谢
  • 有史以来最被低估的运营商。谢谢@salathe!
  • 这将失败低于 5.6.0 并出现以下错误:解析错误:语法错误,意外'。'
猜你喜欢
  • 2017-05-15
  • 2016-05-27
  • 2014-07-30
  • 2017-03-12
  • 2011-03-06
  • 2016-08-29
  • 2023-03-15
  • 2011-07-12
  • 1970-01-01
相关资源
最近更新 更多