Heim  >  Artikel  >  Backend-Entwicklung  >  新写的类工厂函数

新写的类工厂函数

WBOY
WBOYOriginal
2016-06-13 13:51:32896Durchsuche

新写的类工厂函数,请指教

PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->
<?php /** 
 * 中文名称     类创建工厂
 * 
 * 功能描述     实例化类,支持类构造函数多参数功能
 *  
 * @author        魔力一生缘 moliyishengyuan@126.com
 * @package        Lib
 */ 
class ClsFactory {
    /**
     * 创建类对象
     *
     * @param string    $classInfo        类信息
     * @param mixed        $param1            类构造函数参数1,可选
     * @param mixed        $param2            类构造函数参数2,可选
     * ……
     * 
     * @return object | FALSE
     */
    public static function create() {
        // 从参数中获取类信息和类构造函数参数
        $args = func_get_args();
        if (count($args) <= 0) {
            return FALSE;
        }
        
        // 类信息,此处类信息格式为model::Test,对应/model/Test.php文件中的Test类
        $classInfo = array_shift($args);
        $params       = $args;
        
        // 类创建函数实体
        self::_createMain($classInfo, $params);
    }

    /**
     * 创建类主体函数
     *
     * @param array        $classInfo        类信息
     * @param array        $params            类构造函数参数
     * 
     * @return object | FALSE
     */
    private static function _createMain($classInfo, $params) {
        $className = array_pop($classInfo);
        $classPath = SERVER_ROOT . implode('/', $classInfo). '/' . $className . '.php';

        if (!class_exists($className)) {
            include_once $classPath;
        }
        if (!class_exists($className)) {
            return FALSE;
        }
        
        // 通过反射创建类的映射
        $ref = new ReflectionClass($className);
        if ($ref->hasMethod('__construct') && !empty($params)) {
            $obj = $ref->newInstanceArgs($params);  
        } else {  
            $obj = $ref->newInstance();  
        }
        
        return $obj;
    }
}
?>



------解决方案--------------------
这个做什么用?看起来只是起了一个autoloader的作用?
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn