使用反射类将确切数量的参数传递给类构造函数 PHP


Use Reflection class to pass exact number of parameters to class constructor PHP

我正在创建自己的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);

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

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