From 0b7f0b0534030d82768e0555b6efaf6031057cb0 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 25 Sep 2016 17:35:29 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=AF=E6=8C=81=E6=8E=A7=E5=88=B6=E5=99=A8?= =?UTF-8?q?=E7=9A=84=E6=9E=B6=E6=9E=84=E6=96=B9=E6=B3=95=E4=BE=9D=E8=B5=96?= =?UTF-8?q?=E6=B3=A8=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/App.php | 23 ++++++++++++++++++++++- library/think/Loader.php | 2 +- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/library/think/App.php b/library/think/App.php index 0f3375d9..4f08ee1f 100644 --- a/library/think/App.php +++ b/library/think/App.php @@ -221,11 +221,32 @@ class App $reflect = new \ReflectionMethod($method); } $args = self::bindParams($reflect, $vars); - // 记录执行信息 + self::$debug && Log::record('[ RUN ] ' . $reflect->__toString(), 'info'); return $reflect->invokeArgs(isset($class) ? $class : null, $args); } + /** + * 调用反射执行类的实例化 支持依赖注入 + * @access public + * @param string $class 类名 + * @param array $vars 变量 + * @return mixed + */ + public static function invokeClass($class, $vars = []) + { + $reflect = new \ReflectionClass($class); + $constructor = $reflect->getConstructor(); + if ($constructor) { + $args = self::bindParams($constructor, $vars); + } else { + $args[] = Request::instance(); + } + + self::$debug && Log::record('[ RUN ] ' . $reflect->__toString(), 'info'); + return $reflect->newInstanceArgs($args); + } + /** * 绑定参数 * @access public diff --git a/library/think/Loader.php b/library/think/Loader.php index 90780d04..ef86720c 100644 --- a/library/think/Loader.php +++ b/library/think/Loader.php @@ -406,7 +406,7 @@ class Loader } $class = self::parseClass($module, $layer, $name, $appendSuffix); if (class_exists($class)) { - return new $class(Request::instance()); + return App::invokeClass($class); } elseif ($empty && class_exists($emptyClass = self::parseClass($module, $layer, $empty, $appendSuffix))) { return new $emptyClass(Request::instance()); }