2019-04-03 14:08:01 2335瀏覽
今天扣丁學堂PHP培訓老師給大家分享一篇關于PHP反射實際應用,結合實例形式分析了php使用反射實現(xiàn)自動生成文檔、實現(xiàn)MVC架構、實現(xiàn)單元測試等具體應用操作技巧。
<?php class Student { const NORMAL = 1; const FORBIDDEN = 2; /** * 用戶ID * @var 類型 */ public $id; /** * 獲取id * @return int */ public function getId() { return $this->id; } public function setId($id = 1) { $this->id = $id; } } $ref = new ReflectionClass('Student'); $doc = $ref->getDocComment(); echo $ref->getName() . ':' . getComment($ref) , "<br/>"; echo "屬性列表:<br/>"; printf("%-15s%-10s%-40s<br/>", 'Name', 'Access', 'Comment'); $attr = $ref->getProperties(); foreach ($attr as $row) { printf("%-15s%-10s%-40s<br/>", $row->getName(), getAccess($row), getComment($row)); } echo "常量列表:<br/>"; printf("%-15s%-10s<br/>", 'Name', 'Value'); $const = $ref->getConstants(); foreach ($const as $key => $val) { printf("%-15s%-10s<br/>", $key, $val); } echo "<br/><br/>"; echo "方法列表<br/>"; printf("%-15s%-10s%-30s%-40s<br/>", 'Name', 'Access', 'Params', 'Comment'); $methods = $ref->getMethods(); foreach ($methods as $row) { printf("%-15s%-10s%-30s%-40s<br/>", $row->getName(), getAccess($row), getParams($row), getComment($row)); } // 獲取權限 function getAccess($method) { if ($method->isPublic()) { return 'Public'; } if ($method->isProtected()) { return 'Protected'; } if ($method->isPrivate()) { return 'Private'; } } // 獲取方法參數(shù)信息 function getParams($method) { $str = ''; $parameters = $method->getParameters(); foreach ($parameters as $row) { $str .= $row->getName() . ','; if ($row->isDefaultValueAvailable()) { $str .= "Default: {$row->getDefaultValue()}"; } } return $str ? $str : ''; } // 獲取注釋 function getComment($var) { $comment = $var->getDocComment(); // 簡單的獲取了第一行的信息,這里可以自行擴展 preg_match('/\* (.*) *?/', $comment, $res); return isset($res[1]) ? $res[1] : ''; }
Student: 屬性列表: Name Access Comment id Public 用戶ID 常量列表: Name Value NORMAL 1 FORBIDDEN 2 方法列表 Name Access Params Comment getId Public 獲取id setId Public id,Default: 1
$class = new ReflectionClass(ucfirst($controller) . 'Controller'); $controller = $class->newInstance(); if ($class->hasMethod($method)) { $method = $class->getMethod($method); $method->invokeArgs($controller, $arguments); } else { throw new Exception("{$controller} controller method {$method} not exists!"); }
<?php class Calc { public function plus($a, $b) { return $a + $b; } public function minus($a, $b) { return $a - $b; } } function testEqual($method, $assert, $data) { $arr = explode('@', $method); $class = $arr[0]; $method = $arr[1]; $ref = new ReflectionClass($class); if ($ref->hasMethod($method)) { $method = $ref->getMethod($method); $res = $method->invokeArgs(new $class, $data); if($res === $assert){ echo "測試結果正確"; }; } } testEqual('Calc@plus', 3, [1, 2]); echo "<br/>"; testEqual('Calc@minus', -1, [1, 2]);
<?php class DI { protected static $data = []; public function __set($k, $v) { self::$data[$k] = $v; } public function __get($k) { return $this->bulid(self::$data[$k]); } // 獲取實例 public function bulid($className) { // 如果是匿名函數(shù),直接執(zhí)行,并返回結果 if ($className instanceof Closure) { return $className($this); } // 已經(jīng)是實例化對象的話,直接返回 if(is_object($className)) { return $className; } // 如果是類的話,使用反射加載 $ref = new ReflectionClass($className); // 監(jiān)測類是否可實例化 if (!$ref->isInstantiable()) { throw new Exception('class' . $className . ' not find'); } // 獲取構造函數(shù) $construtor = $ref->getConstructor(); // 無構造函數(shù),直接實例化返回 if (is_null($construtor)) { return new $className; } // 獲取構造函數(shù)參數(shù) $params = $construtor->getParameters(); // 解析構造函數(shù) $dependencies = $this->getDependecies($params); // 創(chuàng)建新實例 return $ref->newInstanceArgs($dependencies); } // 分析參數(shù),如果參數(shù)中出現(xiàn)依賴類,遞歸實例化 public function getDependecies($params) { $data = []; foreach($params as $param) { $tmp = $param->getClass(); if (is_null($tmp)) { $data[] = $this->setDefault($param); } else { $data[] = $this->bulid($tmp->name); } } return $data; } // 設置默認值 public function setDefault($param) { if ($param->isDefaultValueAvailable()) { return $param->getDefaultValue(); } throw new Exception('no default value!'); } } class Demo { public function __construct(Calc $calc) { echo $calc->plus(1, 2); } } class Calc { public function plus($a, $b) { return $a + $b; } public function minus($a, $b) { return $a - $b; } } $di = new DI(); $di->calc = 'Calc'; $di->demo = 'Demo'; $di->demo;//輸出結果為3
想要了解更多關于PHP開發(fā)方面內(nèi)容的小伙伴,請關注扣丁學堂PHP培訓官網(wǎng)、微信等平臺,扣丁學堂IT職業(yè)在線學習教育有專業(yè)的PHP講師為您指導,此外扣丁學堂老師精心推出的PHP視頻教程定能讓你快速掌握PHP從入門到精通開發(fā)實戰(zhàn)技能??鄱W堂PHP技術交流群:374332265。
【關注微信公眾號獲取更多學習資料】 【掃碼進入Python全棧開發(fā)免費公開課】