上一篇《手寫PHP API框架之Composer的安裝使用(二)》文章中我們介紹了Composer的安裝使用,這一文我們來介紹一下有關反射的概念介紹。
反射,直觀理解就是根據到達地找到出發地和來源。 反射指在PHP運行狀態中,擴展分析PHP程序,導出或提出關于類、方法、屬性、參數等的詳細信息,包括注釋。這種動態獲取信息以及動態調用對象方法的功能稱為反射API。
不妨先來看一個demo:
<?php function p($msg, $var) { echo($msg.":".print_r($var, true)).PHP_EOL.PHP_EOL; } class Demo { private $id; protected $name; public $skills = []; public function __construct($id, $name, $skills = []) { $this->id = $id; $this->name = $name; $this->skills = $skills; } public function getName() { return $this->name; } public function getSkill() { p('skill', $this->skills); } } $ref = new ReflectionClass('Demo'); if ($ref->isInstantiable()) { p('檢查類是否可實例化isInstantiable', null); } $constructor = $ref->getConstructor(); p('獲取構造函數getConstructor', $constructor); $parameters = $constructor->getParameters(); foreach ($parameters as $param) { p('獲取參數getParameters', $param); } if ($ref->hasProperty('name')) { $attr = $ref->getProperty('name'); p('獲取屬性getProperty', $attr); } $attributes = $ref->getProperties(); foreach ($attributes as $row) { p('獲取屬性列表getProperties', $row->getName()); } if ($ref->hasMethod('getSkill')) { $method = $ref->getMethod('getSkill'); p('獲取方法getMethod', $method); } $methods = $ref->getMethods(); foreach ($methods as $row) { p('獲取方法列表getMethods', $row->getName()); } $instance = $ref->newInstanceArgs([1, 'sai', ['php', 'js']]); p('newInstanceArgs', $instance);
登錄后復制
輸出:
? php git:(main) php reflect.php 檢查類是否可實例化isInstantiable: 獲取構造函數getConstructor:ReflectionMethod Object ( [name] => __construct [class] => Demo ) 獲取參數getParameters:ReflectionParameter Object ( [name] => id ) 獲取參數getParameters:ReflectionParameter Object ( [name] => name ) 獲取參數getParameters:ReflectionParameter Object ( [name] => skills ) 獲取屬性getProperty:ReflectionProperty Object ( [name] => name [class] => Demo ) 獲取屬性列表getProperties:id 獲取屬性列表getProperties:name 獲取屬性列表getProperties:skills 獲取方法getMethod:ReflectionMethod Object ( [name] => getSkill [class] => Demo ) 獲取方法列表getMethods:__construct 獲取方法列表getMethods:getName 獲取方法列表getMethods:getSkill newInstanceArgs:Demo Object ( [id:Demo:private] => 1 [name:protected] => sai [skills] => Array ( [0] => php [1] => js ) )
登錄后復制
demo里面就有使用了ReflectionClass類,當然ReflectionClass類不止于這些方法。