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,

图片转代码服务由CSDN问答提供 功能建议

我在我的一些mvc代码中使用__call魔术来生成可自动加载的表单框架但我遇到了 问题我希望这里的某个人可能有一个解决方法。

__call magic需要两个参数:$ methodName和$ arguments。 这些论点以你所称的args数组的形式返回。 通常,这个函数在你可以这样做的方法上调用,所以将这些参数提供给一个函数:

  call_user_func_array($ methodName,$ arguments); 
  <  / pre> 
 
 

这将使用参数传播方法签名。 我想做一些更复杂的事情。 我试图以相同的方式传播一个类构造函数,通过能够将一个内爆的逗号deliminenated参数数组发送到类构造函数中或直接发送args但这两个都不会产生所需的结果。 当我将一个内爆阵列发送到构造函数中时,PHP认为它是一个字符串,当我发送数组时,它认为它是一个数组。

这是我使用atm的代码:

  public function __call($ method,$ args){
 
返回$ this-&gt; init_element(new $ method($ args ['name'],$ args ['  value'],$ args ['opts'])); 
 
} 
   
 
 

如果我有4个参数传递下去怎么办? 有没有办法可以动态填充构造函数,就像使用call_user_func_array()函数一样?

我可以使用attributes()函数来执行此操作但我会 非常希望能够像我能用功能那样做。

提前致谢,

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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( );

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dpgua04022 2010-09-07 11:38

    I saw the following somewhere around the web:

     call_user_func_array(array($obj, '__construct'), $args);
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题