2014-09-12 157 views
2

如何在类实例化中传递数组作为构造函数参数?传递数组作为类构造函数的参数

abstract class Person { 

    protected function __construct(){ 

    } 

    public static final function __callStatic($name, $arguments){ 
     return new $name($arguments); 
    } 

} 

class Mike extends Person { 

    protected function __construct($age, $hobby){ 
     echo get_called_class().' is '.$age.' years old and likes '.$hobby; 
    } 
} 


// ============================================= 

Person::Mike(15, 'golf'); 

这应该输出

迈克15岁,喜欢打高尔夫球

但我得到的第二个参数Mike的构造缺少的,因为从__callStatic这两个参数都为发数组到$age。我的问题是我怎样才能发送他们作为参数,而不是数组?

+2

这已经有一段时间,因为我用PHP的工作,但你不应该在构造函数,而不是1使用2x_? – Jonast92 2014-09-12 15:48:21

+0

@ Jonast92我的错误。 Thx指出它 – 2014-09-12 15:50:12

回答

2

您可以使用Reflection此:

public static function __callStatic($name, $arguments){ 
    $reflector = new ReflectionClass($name); 
    return $reflector->newInstanceArgs($arguments); 
} 
+0

是的,谢谢! – 2014-09-12 16:00:26

1

使用call_user_func_array()http://fi1.php.net/manual/en/function.call-user-func-array.php和工厂方法:

class Mike extends Person { 

    public static function instantiate($age, $hobby) { 
     return new self($age, $hobby); 
    } 
    protected function __construct($age, $hobby){ 
     echo get_called_class().' is '.$age.' years old and likes '.$hobby; 
    } 
} 

,然后作出迈克像这样:

abstract class Person { 

    protected function __construct(){ 

    } 

    public static final function __callStatic($name, $arguments){ 
     return call_user_func_array(array($name, 'instantiate'), $args); 
    } 

} 
+0

我不能那样做。我需要能够调用'Person :: Mike()' – 2014-09-12 15:56:51

+0

这就是那个。 – Schlaus 2014-09-12 15:57:24

+0

但后来我必须在所有类中实现'instantiate',这并不聪明。 – 2014-09-12 15:59:21

0

您使用的是静态的范围resolutor错误

Person::Mike(15, 'golf'); 

这将意味着你有一个静态方法Mike我在课程Person的旁边,你在静态地调用它。

相反,你要实例Mike

$mike = new Mike(15, 'golf'); 

如果你想从Person调用静态的东西,因为Mike扩展它,Mike也可以静态地调用它。

Mike::staticMethod($args); 
+0

不,我不想那样做。我有一个Person类可以返回人类的实例,我明确不希望能够调用人类的构造函数,这就是为什么他们受到保护。 – 2014-09-12 15:55:35

+0

我添加了一些东西来更好地处理您的静态需求 – Machavity 2014-09-12 15:57:58

相关问题