Static creator with variable number of arguments
I am looking for the best way to have a static creation method at the abstract level in a class family that can have a variable number of arguments in the constructor.
For example, if I know that all extended versions of Foo will have two constructor arguments, I could do this:
abstract class Foo {
abstract public function __construct($arg1,$arg2);
public static function Create(){
$args = func_get_args();
if(count($agrs)!=2) throw new Exception('Invalid number of arguments');
$classname = __CLASS__;
return new $classname($args[0],$args[1]);
}
}
But how about the case where the constructor is not defined and the number of argumunts can vary:
abstract class Foo {
public static function Create(){
$args = func_get_args();
$classname = __CLASS__;
return new $classname($args[0],$args[1],$args[2]); //errors if less than 3 arguments were passed
}
}
class Foo_1 extends Foo {
public function __c开发者_StackOverflowonstruct($arg1){
//some code...
}
}
class Foo_2 extends Foo {
public function __construct($arg1,$arg2,$arg3){
//some code...
}
}
The best I could come up with is to test arguments passed like this:
public static function Create(){
$args = func_get_args();
$classname = __CLASS__;
switch count($args){
case 0: return new $classname();
case 1: return new $classname($args[0]);
case 2: return new $classname($args[0],$args[1]);
//etc....
}
}
The easiest way to do this is to use the Reflection system.
$reflector = new ReflectionClass($className);
$args = array('foo', 'bar');
// $instance will be an instance of $className
// $args should be an array containing the arguments to
// pass to the constructor
$instance = $reflector->newInstanceArgs($args);
精彩评论