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

<?php

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

      

+3


source to share


4 answers


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



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

      

+5


source


$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.

+2


source


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();
$factory
    ->addArgument( '21' )
    ->addArgument( '903' )
    ->addArgument( '1' )
    ->addArgument( 'abc' )
    ->addArgument( 'jackson' )
    ->doSomeFunction();

      

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

+1


source


Try this according to the first example php doc: http://us2.php.net/call_user_func_array

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

      

0


source







All Articles