【PHP高级特性】之反射
生活随笔
收集整理的這篇文章主要介紹了
【PHP高级特性】之反射
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
PHP5 開始提供了完整的反射API。有反射類(ReflectionClass)和反射函數(ReflectionFunction)等,功能大同小異,這里主要以ReflectionClass為列說明。
什么是反射
他是指PHP在運行狀態中,動態的獲取類、方法、屬性、參數、注釋等信息和動態調用對象的方法的功能。
有什么用
可以幫助我們構建復雜的,可擴的運用。比如自動加載插件,自動生成文檔等
代碼示例
該示例為一個通用API入口
HttpApi.php
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.php
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)));總結
以上是生活随笔為你收集整理的【PHP高级特性】之反射的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3dMa如何录制小动画
- 下一篇: 动态规划算法php,php算法学习之动态