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

时间:2013-10-11 14:46:38

标签: php reflection

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

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