2011-01-10 152 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