Passing parameters to class constructor from a wrapper function
Here is the deal. I'm trying to make a function which returns an object. Something like this:
function getObject( $objectName ) {
return new $objectName() ;
}
But i still need to pass params to the class constructor, easiest solution would be passing to the function an array, like this:
function getObject( $objectName, $arr = array() ) {
return new $objectName( $arr ) ;
}
But then i need the class constructor had only 1 argument and exactly array, which is undesired, cause i want to be able to use this function for any class. Here is the solution i came to:
/**
* 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 开发者_StackOverflow社区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
Well, it works just as i want, but looks a bit clumsy to me. Maybe i'm reinventing the wheel and there is another standard solution or something for this kind of problem?
You can use ReflectionClass
to achieve this easily:
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);
}
}
精彩评论