dongye9820 2010-09-07 11:32
浏览 41
已采纳

__call magic在PHP中创建新类

I am using the __call magic within some of my mvc code to produce an autoloadable forms framework but I have ran into a problem I am hoping some one on here might have a work around for.

The __call magic takes two paramters: $methodName and $arguments. The arguments come back as an array of args which you called. Normally this function is called on methods you can do as such so feed these arguments into a function:

call_user_func_array($methodName, $arguments);

And this will propogate the methods signature with the arguments. I am trying to do something a little more complex. I am attempting to propogate a classes constructor the same way, through being able to send maybe a imploded comma deliminenated array of the arguments into the classes constructor or just sending the args in directly but both of these do not produce the required result. When I send an imploded array down into the constructor PHP thinks it's a string and when I send the array it thinks it's an array.

This is the code I am using atm:

public function __call($method, $args){

    return $this->init_element(new $method($args['name'], $args['value'], $args['opts']));

}

What if I had 4 arguments to pass down though? Is there a way I can get it to dynamically fill the constructor just like you can for a function using call_user_func_array()?

I could use an attributes() function to do this but I would really like to be able to do it like I can with functions.

Thanks in advance,

  • 写回答

2条回答 默认 最新

  • dounanyin3179 2010-09-07 11:48
    关注

    Use PHP's reflection classes: (http://php.net/manual/en/class.reflectionclass.php)

    $obj = new ReflectionClass( $classname );

    then

    $ins = $obj->newInstanceArgs( $arguments );

    or

    $ins = $obj->newInstance( );

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器