dpdyh86002
2013-10-29 11:32
浏览 29
已采纳

PHP __call()魔术方法解析参数

I'm working on a project and I want to try and 'lazy-load' objects.

I've setup a simple class using the Magic Method __call($name, $arguments).

What I'm trying to do is pass the $arguments through, not as an array, but as a list of variables:

public function __call($name, $arguments)
{
    // Include the required file, it should probably include some error
    // checking
    require_once(PLUGIN_PATH . '/helpers/' . $name . '.php');

    // Construct the class name
    $class = '\helpers\\' . $name;    

    $this->$name = call_user_func($class.'::factory', $arguments);

}

However, in the method actually being called by the above, $arguments is being passed through as an array and NOT the single variables, E.G.

public function __construct($one, $two = null)
{
    var_dump($one);
    var_dump($two);
}
static public function factory($one, $two = null)
{
    return new self($one, $two);
}

Returns:

array
  0 => string '1' (length=1)
  1 => string '2' (length=1)

null

Does this make sense, does anyone know how to achieve what I'm trying to?

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

我正在研究一个项目,我想尝试'延迟加载'对象。

我使用Magic Method __call($ name,$ arguments)设置了一个简单的类。

我要做的是传递$ arguments 通过,而不是作为数组,但作为变量列表:

  public function __call($ name,$ arguments)
 {
 //包含所需文件, 它应该包含一些错误
 //检查
 require_once(PLUGIN_PATH。'/ helpers /'。$ name。'。php'); 
 
 //构造类名
 $ class ='\ helpers  \\'。  $名称;  
 
 $ this-> $ name = call_user_func($ class。':: factory',$ arguments); 
 
} 
   
 
 

但是 ,在上面实际调用的方法中,$ arguments作为数组传递,而不是单个变量,EG

  public function __construct($ one,$ two)  = null)
 {
 var_dump($ one); 
 var_dump($ two); 
} 
static public function factory($ one,$ two = null)
 {
返回新的自我($ 1)  ,$ 2); 
} 
   
 
 

返回:

  array 
 0 => 字符串'1'(长度= 1)
 1 => 字符串'2'(长度= 1)
 
null 
   
 
 

这是否有意义,是否有人知道如何实现我的目标?

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

1条回答 默认 最新

  • dongwei3120 2013-10-29 11:36
    已采纳

    Try:

    $this->$name = call_user_func_array($class.'::factory', $arguments);
    

    instead of:

    $this->$name = call_user_func($class.'::factory', $arguments);
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题