dongqian6234 2014-02-28 08:39
浏览 61
已采纳

基于字符串创建一个类,并同时传递构造函数参数

I have a piece of code that basically creates an instance of a class on-the-fly:

$class = 'user';
return new $class;

The challenge is that I have the constructor's arguments in an array format and they're obviously different from class to class -- so there is no pattern at all that I can make anything on top of that. There are some workarounds here to extract these arguments from the array and pass it all through in a way like this:

$args = array( 'one', 'two' );
// some code to generate $arg1, $arg2, etc.
return new $class( $arg1, $arg2 );

However, I really prefer to do it in a smarter way. As far as I can see there is no way to make use of call_user_func and call_user_func_array unless I forget about the constructor and initialize it after instantiation.

Update

Basically I'm looking for something like this:

return magic_func( 'className', array('one', 'two') );
  • 写回答

1条回答 默认 最新

  • doufeng5059 2014-02-28 08:41
    关注
    return (new ReflectionClass($class))->newInstanceArgs($args);
    

    See http://php.net/manual/en/reflectionclass.newinstanceargs.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题