2011-01-10 195 views
1

這是交易。 我想做一個函數返回一個對象。事情是這樣的:從包裝函數向類構造函數傳遞參數

function getObject($objectName) { 
    return new $objectName() ; 
} 

,但我仍然需要通過PARAMS在類的構造函數,最簡單的解決方案將被傳遞給函數的數組,像這樣:

function getObject($objectName, $arr = array()) { 
    return new $objectName($arr) ; 
} 

但後來我需要的類構造函數只有1個參數和數組,這是不受歡迎的,因爲我希望能夠爲任何類使用此函數。 這是我來到了解決方案:

/** 
* Test class 
*/ 
class Class1 { 
    /** 
    * Class constructor just to check if the function below works 
    */ 
    public function __construct($foo, $bar) { 
     echo $foo . ' _ ' . $bar ; 
    } 
} 

/** 
* This function retrns a class $className object, all that goes after first argument passes to the object class constructor as params 
* @param String $className - class name 
* @return Object - desired object 
*/ 
function loadClass($className) { 
    $vars = func_get_args() ; // get arguments 
    unset($vars[ 0 ]) ; // unset first arg, which is $className 
    // << Anonymous function code start >> 
    $code = 'return new ' . $className . '(' ; 
    $auxCode = array() ; 
    foreach($vars as $val) 
     $auxCode[] = 'unserialize(stripslashes(\'' 
     .    addslashes((serialize($val))) . '\'))' ; 
    $code .= implode(',', $auxCode) . ');' ; 
    // << Anonymous function code end >> 
    $returnClass = create_function('', $code) ; // create the anonymous func 
    return $returnClass($vars) ; // return object 
} 

$obj = loadClass('Class1', 'l\'ol', 'fun') ; // test 

好,它的工作原理就像我想要的,但看起來有點笨拙的我。也許我正在重新發明輪子,還有另一種標準解決方案或者這種問題?

回答

5

您可以使用ReflectionClass輕鬆實現這一點:

function getObject($objectName, $arr = array()) { 
    if (empty($arr)) { 
     // Assumes you correctly pass nothing or array() in the second argument 
     // and that the constructor does accept no arguments 
     return new $objectName(); 
    } else { 
     // Similar to call_user_func_array() but on an object's constructor 
     // May throw an exception if you don't pass the correct argument set 
     // or there's no known constructor other than the default (arg-less) 
     $rc = new ReflectionClass($objectName); 
     return $rc->newInstanceArgs($arr); 
    } 
} 
+1

甜!反思......有什麼不能做的?! :) – kander 2011-01-10 19:03:30