PHP反射實(shí)際應(yīng)用示例
本文實(shí)例講述了PHP反射實(shí)際應(yīng)用。分享給大家供大家參考,具體如下:
1.自動(dòng)生成文檔
根據(jù)反射的分析類(lèi),接口,函數(shù)和方法的內(nèi)部結(jié)構(gòu),方法和函數(shù)的參數(shù),以及類(lèi)的屬性和方法,可以自動(dòng)生成文檔。
<?php class Student { const NORMAL = 1; const FORBIDDEN = 2; /** * 用戶(hù)ID * @var 類(lèi)型 */ 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(); // 簡(jiǎn)單的獲取了第一行的信息,這里可以自行擴(kuò)展 preg_match('/\* (.*) *?/', $comment, $res); return isset($res[1]) ? $res[1] : ''; }
輸出結(jié)果:
Student:
屬性列表:
Name Access Comment
id Public 用戶(hù)ID
常量列表:
Name Value
NORMAL 1
FORBIDDEN 2
方法列表
Name Access Params Comment
getId Public 獲取id
setId Public id,Default: 1
2.實(shí)現(xiàn) MVC 架構(gòu)
現(xiàn)在好多框架都是 MVC 的架構(gòu),根據(jù)路由信息定位控制器($controller) 和方法($method) 的名稱(chēng),之后使用反射實(shí)現(xiàn)自動(dòng)調(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.實(shí)現(xiàn)單元測(cè)試
一般情況下我們會(huì)對(duì)函數(shù)和類(lèi)進(jìn)行測(cè)試,判斷其是否能夠按我們預(yù)期返回結(jié)果,我們可以用反射實(shí)現(xiàn)一個(gè)簡(jiǎn)單通用的類(lèi)測(cè)試用例。
<?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 "測(cè)試結(jié)果正確"; }; } } testEqual('Calc@plus', 3, [1, 2]); echo "<br/>"; testEqual('Calc@minus', -1, [1, 2]);
這是類(lèi)的測(cè)試方法,也可以利用反射實(shí)現(xiàn)函數(shù)的測(cè)試方法。
<?php function title($title, $name) { return sprintf("%s. %s\r\n", $title, $name); } $function = new ReflectionFunction('title'); echo $function->invokeArgs(array('Dr', 'Phil')); ?>
這里只是我簡(jiǎn)單寫(xiě)的一個(gè)測(cè)試用例,PHPUnit 單元測(cè)試框架很大程度上依賴(lài)了 Reflection 的特性,可以了解下。
4.配合 DI 容器解決依賴(lài)
Laravel 等許多框架都是使用 Reflection 解決依賴(lài)注入問(wèn)題,具體可查看 Laravel 源碼進(jìn)行分析。
下面我們代碼簡(jiǎn)單實(shí)現(xiàn)一個(gè) DI 容器演示 Reflection 解決依賴(lài)注入問(wèn)題。
<?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]); } // 獲取實(shí)例 public function bulid($className) { // 如果是匿名函數(shù),直接執(zhí)行,并返回結(jié)果 if ($className instanceof Closure) { return $className($this); } // 已經(jīng)是實(shí)例化對(duì)象的話(huà),直接返回 if(is_object($className)) { return $className; } // 如果是類(lèi)的話(huà),使用反射加載 $ref = new ReflectionClass($className); // 監(jiān)測(cè)類(lèi)是否可實(shí)例化 if (!$ref->isInstantiable()) { throw new Exception('class' . $className . ' not find'); } // 獲取構(gòu)造函數(shù) $construtor = $ref->getConstructor(); // 無(wú)構(gòu)造函數(shù),直接實(shí)例化返回 if (is_null($construtor)) { return new $className; } // 獲取構(gòu)造函數(shù)參數(shù) $params = $construtor->getParameters(); // 解析構(gòu)造函數(shù) $dependencies = $this->getDependecies($params); // 創(chuàng)建新實(shí)例 return $ref->newInstanceArgs($dependencies); } // 分析參數(shù),如果參數(shù)中出現(xiàn)依賴(lài)類(lèi),遞歸實(shí)例化 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)容感興趣的讀者可查看本站專(zhuān)題:《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語(yǔ)法入門(mén)教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
- PHP的反射動(dòng)態(tài)獲取類(lèi)方法、屬性、參數(shù)操作示例
- php面試實(shí)現(xiàn)反射注入的詳細(xì)方法
- PHP反射原理與用法深入分析
- php提供實(shí)現(xiàn)反射的方法和實(shí)例代碼
- PHP進(jìn)階學(xué)習(xí)之反射基本概念與用法分析
- php反射學(xué)習(xí)之不用new方法實(shí)例化類(lèi)操作示例
- PHP反射學(xué)習(xí)入門(mén)示例
- 用PHP的反射實(shí)現(xiàn)委托模式的講解
- 淺析PHP類(lèi)的反射來(lái)實(shí)現(xiàn)依賴(lài)注入過(guò)程
- PHP基于反射機(jī)制實(shí)現(xiàn)自動(dòng)依賴(lài)注入的方法詳解
- PHP基于反射獲取一個(gè)類(lèi)中所有的方法
- PHP反射基礎(chǔ)知識(shí)回顧
相關(guān)文章
PHP 使用header函數(shù)設(shè)置HTTP頭的示例解析 表頭
本篇文章是對(duì)PHP使用header函數(shù)設(shè)置HTTP頭的示例進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06PHP+mysql實(shí)現(xiàn)的三級(jí)聯(lián)動(dòng)菜單功能示例
這篇文章主要介紹了PHP+mysql實(shí)現(xiàn)的三級(jí)聯(lián)動(dòng)菜單功能,涉及mysql數(shù)據(jù)庫(kù)創(chuàng)建、數(shù)據(jù)添加及php讀取mysql、創(chuàng)建聯(lián)動(dòng)菜單相關(guān)操作技巧,需要的朋友可以參考下2019-02-02在WordPress中獲取數(shù)據(jù)庫(kù)字段內(nèi)容和添加主題設(shè)置菜單
這篇文章主要介紹了在WordPress中獲取數(shù)據(jù)庫(kù)字段內(nèi)容和添加主題設(shè)置菜單的方法,分別講解了get_option()函數(shù)和add_theme_page()函數(shù)的用法,需要的朋友可以參考下2016-01-01PHP獲取redis里不存在的6位隨機(jī)數(shù)應(yīng)用示例【設(shè)置24小時(shí)過(guò)時(shí)】
這篇文章主要介紹了PHP獲取redis里不存在的6位隨機(jī)數(shù)的方法,可設(shè)置24小時(shí)過(guò)時(shí)限制,涉及php字符串及數(shù)據(jù)庫(kù)相關(guān)操作技巧,需要的朋友可以參考下2017-06-06PHP判斷數(shù)據(jù)庫(kù)中的記錄是否存在的方法
這篇文章主要介紹了PHP判斷數(shù)據(jù)庫(kù)中的記錄是否存在的方法,通過(guò)mysql_num_rows對(duì)查詢(xún)結(jié)果進(jìn)行判斷來(lái)實(shí)現(xiàn)這一功能,非常實(shí)用,需要的朋友可以參考下2014-11-11php下判斷數(shù)組中是否存在相同的值array_unique
今天在改一個(gè)N久以前寫(xiě)的程序 突然碰到一個(gè)問(wèn)題 假設(shè)有一個(gè)數(shù)組$a中存在幾個(gè)value 我如何判斷這些value當(dāng)中是否存在相同的值呢? 翻了好多資料,也問(wèn)了兵哥哥,給我一些思路,想自己寫(xiě)來(lái)著~~~ 還是不肯放棄百度,最后搞了一次,居然找到這么一個(gè)函數(shù) array_unique爽大了。2008-03-03PHP實(shí)現(xiàn)的消息實(shí)時(shí)推送功能【基于反ajax推送】
這篇文章主要介紹了PHP實(shí)現(xiàn)的消息實(shí)時(shí)推送功能,結(jié)合實(shí)例形式分析了php基于反ajax推送實(shí)現(xiàn)的消息實(shí)時(shí)推送前臺(tái)ajax提交、后臺(tái)數(shù)據(jù)處理等相關(guān)操作技巧,需要的朋友可以參考下2018-03-03