我有个需求
比如下面function Factory($classname) { return new $classname();}
$tiger = Factory(“Tiger”);
但如果我Tiger类构造方法有参数的话,如何通过工厂来传参呢?
要适应所有类:不用构造方法有不同的参数个数, 直接在构造方法后面加上参数貌似行不通,并且我也不希望通过传array的办法来解决。
回复内容:
我有个需求
比如下面function Factory($classname) { return new $classname();}
$tiger = Factory(“Tiger”);
但如果我Tiger类构造方法有参数的话,如何通过工厂来传参呢?
要适应9来源gaodai#ma#com搞@代~码$网搞gaodaima代码所有类:不用构造方法有不同的参数个数, 直接在构造方法后面加上参数貌似行不通,并且我也不希望通过传array的办法来解决。
反射一下
<code class="lang-php">class test{ function __construct($config = ''){ if(!empty($config)){ var_dump($config); }else{ echo 'no params'; } }}function Factory($classname, $params='') { if(!empty($params) ){ $reflect = new ReflectionClass($classname); return $reflect->newInstanceArgs($params); }else{ return new $classname(); }}$config_test = array('a','b','c');Factory('test');Factory('test', $config_test);</code>
参考:
http://www.php.net/manual/zh/class.reflectionclass.php
http://www.600mhz.net/php/php_runtime_instance_class_and_pass_parameters.html/comment-page-1