新写的类工厂函数

WBOY
Release: 2016-06-13 13:51:32
Original
895 people have browsed it

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

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

Copy after login


------解决方案--------------------
这个做什么用?看起来只是起了一个autoloader的作用?
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!