这是合约。 我正在尝试创建一个返回对象的函数。像这样:
function getObject( $objectName ) {
return new $objectName() ;
}
但是我仍然需要将params传递给类构造函数,最简单的解决方案是将函数传递给数组,如下所示:
function getObject( $objectName, $arr = array() ) {
return new $objectName( $arr ) ;
}
但是后来我需要类构造函数只有一个参数和完全数组,这是不希望的,因为我希望能够将此函数用于任何类。 这是我来的解决方案:
/**
* 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
嗯,它正如我想的那样工作,但对我来说看起来有点笨拙。也许我正在重新发明轮子,还有另一种标准的解决方案或类似的问题吗?
答案 0 :(得分: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);
}
}