2014-03-19 67 views
0

代碼看起來是這樣的:創建功能使單例類PHP

function make($class,$singleton,array $params=array()) 
{ 
    switch(count($params)) 
    { 
     case 0: 
      return $class::$singleton(); 
     case 1: 
      return $class::$singleton($params[0]); 
     case 2: 
      return $class::$singleton($params[0],$params[1]); 
     case 3: 
      return $class::$singleton($params[0],$params[1],$params[2]); 
     case 4: 
      return $class::$singleton($params[0],$params[1],$params[2],$params[3]); 
     case 5: 
      return $class::$singleton($params[0],$params[1],$params[2],$params[3],$params[4]); 
     default: 
      //do something here... 
    } 
} 

例如:

class Test 
{ 
    private function __construct() 
    { 

    } 

    public static function getInstance($name) 
    { 
     return new Test; 
    } 
} 

$t=make('Test','getInstance',array('something value here')); 

就OK了,但類有單方法比5變大,有什麼代碼默認開關?有人可以幫助我?

+2

這可以幫助你:HTTP://計算器.com/questions/1422652/how-to-pass-variable-number-of-arguments-to-php-function – Mike

+0

爲什麼不通過整個數組而不管它是多少位? –

回答

0

您可以通過使用call_user_func_array

function make($class, $singleton, array $params = array()) 
{ 
return call_user_func_array(array($class, $singleton), $params); 
} 

刪除您的轉移或等待PHP5.6釋放,你就可以做到這一點:

return $class:$singleton(...$params);