Home > Backend Development > PHP Tutorial > factory - PHP工程模式如何传入参数

factory - PHP工程模式如何传入参数

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:49:26
Original
1309 people have browsed it

我有个需求

比如下面 function Factory($classname) { return new $classname(); }

$tiger = Factory("Tiger");

但如果我Tiger类构造方法有参数的话,如何通过工厂来传参呢?

要适应所有类: 不用构造方法有不同的参数个数, 直接在构造方法后面加上参数貌似行不通, 并且我也不希望通过传array的办法来解决。

回复内容:

我有个需求

比如下面 function Factory($classname) { return new $classname(); }

$tiger = Factory("Tiger");

但如果我Tiger类构造方法有参数的话,如何通过工厂来传参呢?

要适应所有类: 不用构造方法有不同的参数个数, 直接在构造方法后面加上参数貌似行不通, 并且我也不希望通过传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>
Copy after login

参考:
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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template