2012-04-21 69 views
1

我創建了一個__call()方法來動態加載方法。我想要解決的一個問題是__call()使得從該調用傳遞的所有參數都成爲數組。這是我的代碼使用__call()將參數傳遞給一個方法,該方法需要多個而不是一個數組

public function __call($method, $params) 
{ 
    if (count($params) <= 1) 
      $params = $params[0]; 

    foreach (get_object_vars($this) as $property => $value) { 

     $class = '\\System\\' . ucfirst(str_replace('_', '', $property)) . '_Helper'; 

     if (strpos($method, str_replace('_', '', $property)) !== false) { 

      if (!in_array($class, get_declared_classes())) 
       $this->$property = new $class($params); 

      $error = $method . ' doesn\'t exist in class ' . $class; 

      return (method_exists($class, $method) ? $this->$property->$method($params) : $error); 
     } 
    } 
} 

的問題是,我可以僅佔具有一個參數的陣列,但我的一些方法採取這限制了__call()方法的動態性質一個以上的參數。

如何將數組轉換爲動態傳遞的方法參數?

所以

array(0 => 'stuff1', 1 => 'stuff2'); 

可以根據

$this->->helper->test($param1, $param2); 

,而不是

$this->helper->test($params); 

通過與當前的設計,我需要訪問像

public function test($params) 
{ 
    print_r($params); 
    echo $param[0]; 
} 
參數

,但我要像

​​

牢記,有些方法需要超過2個參數使用它以傳統的方式,產生的原因是,如果我有傳統風格類的方法不是我,我創建將需要將所有參數調用轉換爲數組索引指針。

編輯:

按一個答案

return (method_exists($class, $method) ? call_user_func_array(array($this->$property, $method), $params) : $error); 

將這項工作?

回答

3

可與call_user_func_array

call_user_func_array(array($this->$property, $method), $params); 

或通過reflection

+0

我只是返回,而不是像我最初調用方法? – Eli 2012-04-21 07:49:23

0

看起來像你需要call_user_func_array()This comment也很有用。

(另外,還要考慮拋出異常,而不是僅僅返回錯誤的字符串。)

+0

燁做的,我之前還在我的設計功能我得到的例外=) – Eli 2012-04-21 07:53:57

相關問題