具有可变数量参数的PHP Factory类

时间:2012-03-09 19:19:10

标签: php oop factory

我要创建一个(类)工厂类,接受可变数量的参数并将它们传递给它将调用的类

<?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);

我收到此错误

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

4 个答案:

答案 0 :(得分:5)

找到关于ReflectionClass的答案。这似乎效果最好

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

答案 1 :(得分:2)

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

或者使用 ReflectionClass 或者使用属性注入构造函数注入。

答案 2 :(得分:1)

我认为你应该通过不将值传递给构造函数来解决问题,而是通过链接来解决问题。

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. */
    }
}

你可以像这样使用它:

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

我希望至少让你朝着有用的方向前进。你可以用这种模式做各种疯狂的事情。

答案 3 :(得分:0)

试试这个,根据php doc第一个例子:http://us2.php.net/call_user_func_array

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