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