PHP Factory class with variable number of arguments

I have to create a factory class that takes a variable number of arguments and passes them to the class that it will call


class A {
    private $a;
    private $b;
    private $c;
    public function __construct($a=1, $b=2, $c=3){
        $this->a = $a;
        $this->b = $b;
        $this->c = $c;

class B {
    private $foo;

    public function __construct(){
        $args = func_get_args();
        $this->foo = call_user_func_array(array('A', '__construct'), $args);

    public function getObject(){
        return $this->foo;

$b = new B(10, 20, 30);  
var_dump($b->getObject()); // should return equivalent of new A(10,20,30);


I am getting this error

PHP Warning:  call_user_func_array() expects parameter 1 to be a valid callback, non-static method A::__construct() cannot be called statically



source to share

4 answers

Found this answer by reading ReflectionClass . This seems to work best

class Factory {
    # ...
    public function __construct(){
        $args = func_get_args();
        $a = new ReflectionClass('A');
        $this->foo = $a->newInstanceArgs($args);
    # ...




$class = "A";
$foo = new $class(1, 2, 56); // i think this not solve your problem


Or use ReflectionClass or maybe constructor injection with property injection.



I think you should solve the problem by not passing values ​​to the constructor but chaining.

class MyFactory() {
    public $data;

    public static function factory( $data = null ) {
        return new MyFactory( $data );
    public function addArgument( $argValue ) {
        $this->data[] = $argValue;
        return $this;

    public function doSomeFunction() {
        $data = $this->data; //is an array, so you can loop through and do whatever.
        /* now your arbitrarily long array of data points can be used to do whatever. */


And you can use it like this:

$factory = MyFactory::factory();
    ->addArgument( '21' )
    ->addArgument( '903' )
    ->addArgument( '1' )
    ->addArgument( 'abc' )
    ->addArgument( 'jackson' )


I hope that at least you go in the right direction. You can do all sorts of crazy things with this type of drawing.



Try this according to the first example php doc:

$this->foo = call_user_func_array(array(new A, '__construct'), $args);




All Articles