Better way to dynamically load instance w/ args
Posted: Fri Feb 11, 2011 6:25 pm
I have a abstract class which has a getinstance function in. The problem I have is with arguments. Right now I am using an eval to pass those arguments to the class constructor. Is there a better way to do this.
See there HERE! part:
See there HERE! part:
Code: Select all
abstract class Core {
/**
* Arry of the class instances
*
* @var array
*/
static protected $_instances = array();
/**
* Retrieves the singleton instance of this class.
* This is completely self loading
*
* @return instance of this class
*/
static public function getInstance() {
//Get the called class so we know which class to load
$class = get_called_class();
//If there is not an already loaded instance
if (!isset(self::$_instances[$class])) {
//If there were no passed in arguments
if (func_num_args() == 0) {
//Make the new class instance
self::$_instances[$class] = new $class();
} else {
//--------------- HERE! ------------------
$args = func_get_args();
$eval = 'self::$_instances[$class] = new $class(';
for ($i = 0, $count = func_num_args(); $i < $count; ++$i) {
$eval .= '$args['.$i.'],';
}
$eval = substr($eval, 0, -1);
$eval .= ');';
eval($eval);
}
}
return self::$_instances[$class];
}
}