濮阳杆衣贸易有限公司

主頁 > 知識庫 > PHP反射實(shí)際應(yīng)用示例

PHP反射實(shí)際應(yīng)用示例

熱門標(biāo)簽:阿里云400電話申請加工單 智能電話機(jī)器人排名前十名南京 保定crm外呼系統(tǒng)運(yùn)營商 西區(qū)企業(yè)怎么做地圖標(biāo)注入駐 地下城堡2圖九地圖標(biāo)注 九江外呼系統(tǒng) 抖音有個(gè)地圖標(biāo)注是什么意思 七魚外呼系統(tǒng)停用嗎 海南人工外呼系統(tǒng)有效果嗎

本文實(shí)例講述了PHP反射實(shí)際應(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%-40sbr/>", 'Name', 'Access', 'Comment');
$attr = $ref->getProperties();
foreach ($attr as $row) {
  printf("%-15s%-10s%-40sbr/>", $row->getName(), getAccess($row), getComment($row));
}
echo "常量列表:br/>";
printf("%-15s%-10sbr/>", 'Name', 'Value');
$const = $ref->getConstants();
foreach ($const as $key => $val) {
  printf("%-15s%-10sbr/>", $key, $val);
}
echo "br/>br/>";
echo "方法列表br/>";
printf("%-15s%-10s%-30s%-40sbr/>", 'Name', 'Access', 'Params', 'Comment');
$methods = $ref->getMethods();
foreach ($methods as $row) {
  printf("%-15s%-10s%-30s%-40sbr/>", $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();
  // 簡單的獲取了第一行的信息,這里可以自行擴(kuò)展
  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.實(shí)現(xiàn) MVC 架構(gòu)

現(xiàn)在好多框架都是 MVC 的架構(gòu),根據(jù)路由信息定位控制器($controller) 和方法($method) 的名稱,之后使用反射實(shí)現(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.實(shí)現(xiàn)單元測試

一般情況下我們會對函數(shù)和類進(jìn)行測試,判斷其是否能夠按我們預(yù)期返回結(jié)果,我們可以用反射實(shí)現(xiàn)一個(gè)簡單通用的類測試用例。

?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]);

這是類的測試方法,也可以利用反射實(shí)現(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'));
?>

這里只是我簡單寫的一個(gè)測試用例,PHPUnit 單元測試框架很大程度上依賴了 Reflection 的特性,可以了解下。

4.配合 DI 容器解決依賴

Laravel 等許多框架都是使用 Reflection 解決依賴注入問題,具體可查看 Laravel 源碼進(jìn)行分析。

下面我們代碼簡單實(shí)現(xiàn)一個(gè) 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]);
  }
  // 獲取實(shí)例
  public function bulid($className)
  {
    // 如果是匿名函數(shù),直接執(zhí)行,并返回結(jié)果
    if ($className instanceof Closure) {
      return $className($this);
    }
    // 已經(jīng)是實(shí)例化對象的話,直接返回
    if(is_object($className)) {
      return $className;
    }
    // 如果是類的話,使用反射加載
    $ref = new ReflectionClass($className);
    // 監(jiān)測類是否可實(shí)例化
    if (!$ref->isInstantiable()) {
      throw new Exception('class' . $className . ' not find');
    }
    // 獲取構(gòu)造函數(shù)
    $construtor = $ref->getConstructor();
    // 無構(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)依賴類,遞歸實(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)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》

希望本文所述對大家PHP程序設(shè)計(jì)有所幫助。

您可能感興趣的文章:
  • PHP的反射動態(tài)獲取類方法、屬性、參數(shù)操作示例
  • php面試實(shí)現(xiàn)反射注入的詳細(xì)方法
  • PHP反射原理與用法深入分析
  • php提供實(shí)現(xiàn)反射的方法和實(shí)例代碼
  • PHP進(jìn)階學(xué)習(xí)之反射基本概念與用法分析
  • php反射學(xué)習(xí)之不用new方法實(shí)例化類操作示例
  • PHP反射學(xué)習(xí)入門示例
  • 用PHP的反射實(shí)現(xiàn)委托模式的講解
  • 淺析PHP類的反射來實(shí)現(xiàn)依賴注入過程
  • PHP基于反射機(jī)制實(shí)現(xiàn)自動依賴注入的方法詳解
  • PHP基于反射獲取一個(gè)類中所有的方法
  • PHP反射基礎(chǔ)知識回顧

標(biāo)簽:九江 昭通 十堰 甘肅 涼山 韶關(guān) 遼陽 梅河口

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PHP反射實(shí)際應(yīng)用示例》,本文關(guān)鍵詞  PHP,反射,實(shí)際,應(yīng)用,示例,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《PHP反射實(shí)際應(yīng)用示例》相關(guān)的同類信息!
  • 本頁收集關(guān)于PHP反射實(shí)際應(yīng)用示例的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    呼图壁县| 松阳县| 平远县| 普兰店市| 县级市| 怀安县| 鄂尔多斯市| 赤水市| 武宁县| 伊川县| 汤原县| 吉隆县| 乌苏市| 平乡县| 新兴县| 酉阳| 台前县| 西宁市| 随州市| 巴塘县| 呈贡县| 大港区| 新沂市| 太仓市| 宜兴市| 垦利县| 泰和县| 诏安县| 长丰县| 邳州市| 安达市| 辽中县| 休宁县| 竹山县| 高邑县| 保亭| 舞钢市| 沙坪坝区| 定西市| 若羌县| 青河县|