PHP反射實際應(yīng)用示例
本文實例講述了PHP反射實際應(yīng)用。分享給大家供大家參考,具體如下:
1.自動生成文檔
根據(jù)反射的分析類,接口,函數(shù)和方法的內(nèi)部結(jié)構(gòu),方法和函數(shù)的參數(shù),以及類的屬性和方法,可以自動生成文檔。
<?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)); } // 獲取權(quán)限 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] : ''; }
輸出結(jié)果:
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
2.實現(xiàn) MVC 架構(gòu)
現(xiàn)在好多框架都是 MVC 的架構(gòu),根據(jù)路由信息定位控制器($controller) 和方法($method) 的名稱,之后使用反射實現(xiàn)自動調(diào)用。
$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!"); }
3.實現(xiàn)單元測試
一般情況下我們會對函數(shù)和類進行測試,判斷其是否能夠按我們預(yù)期返回結(jié)果,我們可以用反射實現(xiàn)一個簡單通用的類測試用例。
<?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 "測試結(jié)果正確"; }; } } testEqual('Calc@plus', 3, [1, 2]); echo "<br/>"; testEqual('Calc@minus', -1, [1, 2]);
這是類的測試方法,也可以利用反射實現(xiàn)函數(shù)的測試方法。
<?php function title($title, $name) { return sprintf("%s. %s\r\n", $title, $name); } $function = new ReflectionFunction('title'); echo $function->invokeArgs(array('Dr', 'Phil')); ?>
這里只是我簡單寫的一個測試用例,PHPUnit 單元測試框架很大程度上依賴了 Reflection 的特性,可以了解下。
4.配合 DI 容器解決依賴
Laravel 等許多框架都是使用 Reflection 解決依賴注入問題,具體可查看 Laravel 源碼進行分析。
下面我們代碼簡單實現(xiàn)一個 DI 容器演示 Reflection 解決依賴注入問題。
<?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í)行,并返回結(jié)果 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'); } // 獲取構(gòu)造函數(shù) $construtor = $ref->getConstructor(); // 無構(gòu)造函數(shù),直接實例化返回 if (is_null($construtor)) { return new $className; } // 獲取構(gòu)造函數(shù)參數(shù) $params = $construtor->getParameters(); // 解析構(gòu)造函數(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; } // 設(shè)置默認(rèn)值 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;//輸出結(jié)果為3
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
相關(guān)文章
PHP 使用header函數(shù)設(shè)置HTTP頭的示例解析 表頭
本篇文章是對PHP使用header函數(shù)設(shè)置HTTP頭的示例進行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06PHP+mysql實現(xiàn)的三級聯(lián)動菜單功能示例
這篇文章主要介紹了PHP+mysql實現(xiàn)的三級聯(lián)動菜單功能,涉及mysql數(shù)據(jù)庫創(chuàng)建、數(shù)據(jù)添加及php讀取mysql、創(chuàng)建聯(lián)動菜單相關(guān)操作技巧,需要的朋友可以參考下2019-02-02在WordPress中獲取數(shù)據(jù)庫字段內(nèi)容和添加主題設(shè)置菜單
這篇文章主要介紹了在WordPress中獲取數(shù)據(jù)庫字段內(nèi)容和添加主題設(shè)置菜單的方法,分別講解了get_option()函數(shù)和add_theme_page()函數(shù)的用法,需要的朋友可以參考下2016-01-01PHP獲取redis里不存在的6位隨機數(shù)應(yīng)用示例【設(shè)置24小時過時】
這篇文章主要介紹了PHP獲取redis里不存在的6位隨機數(shù)的方法,可設(shè)置24小時過時限制,涉及php字符串及數(shù)據(jù)庫相關(guān)操作技巧,需要的朋友可以參考下2017-06-06php下判斷數(shù)組中是否存在相同的值array_unique
今天在改一個N久以前寫的程序 突然碰到一個問題 假設(shè)有一個數(shù)組$a中存在幾個value 我如何判斷這些value當(dāng)中是否存在相同的值呢? 翻了好多資料,也問了兵哥哥,給我一些思路,想自己寫來著~~~ 還是不肯放棄百度,最后搞了一次,居然找到這么一個函數(shù) array_unique爽大了。2008-03-03PHP實現(xiàn)的消息實時推送功能【基于反ajax推送】
這篇文章主要介紹了PHP實現(xiàn)的消息實時推送功能,結(jié)合實例形式分析了php基于反ajax推送實現(xiàn)的消息實時推送前臺ajax提交、后臺數(shù)據(jù)處理等相關(guān)操作技巧,需要的朋友可以參考下2018-03-03