PHP5 開始提供了完整的反射API。有反射類(ReflectionClass)和反射函數(ReflectionFunction)等,功能大同小異,這裏主要以ReflectionClass爲列說明。php
什麼是反射
他是指PHP在運行狀態中,動態的獲取類、方法、屬性、參數、註釋等信息和動態調用對象的方法的功能。json
有什麼用
能夠幫助咱們構建複雜的,可擴的運用。好比自動加載插件,自動生成文檔等app
代碼示例
該示例爲一個通用API入口函數
HttpApi.phpthis
namespace twinkle\service\http; class HttpApi { private $class; public function __construct($class) { $this->class = $class; } public function parseRequest($method,$params = []) { $class = new \ReflectionClass($this->class); $instance = $class->newInstanceArgs($params); $method = $class->getMethod($method); $args = []; foreach ($method->getParameters() as $param) { $name = $param->getName(); if (isset($params[$name])) { $args[$name] = $params[$name]; } else { try { $args[$name] = $param->getDefaultValue(); } catch (\Exception $e) { throw new RequestException( '請求參數不合未能', 500 ); } } } return [$instance,$method,$args]; } }
NotFoundService.phpspa
namespace app\services; use app\base\Service; class NotFoundService extends Service { public function error() { return $this->format(['status' => 1, 'msg' => '請求不合法,請確認service和method是否存在']); } }
使用範例插件
$params = $_REQUEST; $serviceName= isset($params['service']) ? $params['service'] : 'NotFound'; $methodName= isset($params['method']) ? $params['method'] : 'error'; $class = '\\app\\services\\' . Str::ucWords($serviceName) . 'Service'; list($instance, $method, $args) = (new HttpApi($class))->parseRequest($methodName, $params); echo json_encode(($method->invokeArgs($instance, $args)));