2

我正在创建自己的 MVC 框架,我处理模型创建的方式如下:

class ModelFactory {
    public function __construct() {
        parent::__construct();
    }

    public static function Create($model, $params = array()) {
        if ( ! empty($model)) { 
            $model = ucfirst(strtolower($model));
            $path  = 'application/models/' . $model . '.php';

            if (file_exists($path)) {
                $path           = rtrim(str_replace("/", "\\", $path), '.php');

                $modelConstruct = new \ReflectionMethod($path, '__construct');
                $numParams      = $modelConstruct->getNumberOfParameters();

                //fill up missing holes with null values
                if (count($params) != $numParams) {
                    $tempArray = array_fill(0, $numParams, null);
                    $params    = ($params + $tempArray);
                }


                //instead of thi
                return new $path($params);

               //I want to DO THIS 
               return new $path($param1, $param2, $param3 ... $paramN) 
               //where $paramN is the last value from $params array
            }
        }

        return null;
    }
}

一个简单的模型示例:

   class UsersModel {
        public function __construct($userID, $userName) {
           //values of these parameters should be passed from Create function
           var_dump($userID, $userName);
        }
   }

解决了:

感谢schokocappucino & pozs我通过这样做修复了它:

$modelConstruct = new \ReflectionMethod($path, '__construct');
$numParams      = $modelConstruct->getNumberOfParameters();

if (count($params) != $numParams) {
    $tempArray = array_fill(0, $numParams, '');
    $params    = ($params + $tempArray);
}

return (new \ReflectionClass($path))->newInstanceArgs($params);
4

2 回答 2

2

要使用反射获取类的构造函数,请使用ReflectionClass::getConstructor().
要使用参数列表创建一个新实例(使用构造函数),请使用ReflectionClass::newInstanceArgs()

于 2013-10-11T14:52:16.993 回答
2

return (new ReflectionClass($path))->newInstanceArgs($params);

于 2013-10-11T14:54:35.203 回答