上一篇《手寫(xiě)PHP API框架之Composer的安裝使用(二)》文章中我們介紹了Composer的安裝使用,這一文我們來(lái)介紹一下有關(guān)反射的概念介紹。
反射,直觀理解就是根據(jù)到達(dá)地找到出發(fā)地和來(lái)源。 反射指在PHP運(yùn)行狀態(tài)中,擴(kuò)展分析PHP程序,導(dǎo)出或提出關(guān)于類(lèi)、方法、屬性、參數(shù)等的詳細(xì)信息,包括注釋。這種動(dòng)態(tài)獲取信息以及動(dòng)態(tài)調(diào)用對(duì)象方法的功能稱(chēng)為反射API。
不妨先來(lái)看一個(gè)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('檢查類(lèi)是否可實(shí)例化isInstantiable', null); } $constructor = $ref->getConstructor(); p('獲取構(gòu)造函數(shù)getConstructor', $constructor); $parameters = $constructor->getParameters(); foreach ($parameters as $param) { p('獲取參數(shù)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);
登錄后復(fù)制
輸出:
? php git:(main) php reflect.php 檢查類(lèi)是否可實(shí)例化isInstantiable: 獲取構(gòu)造函數(shù)getConstructor:ReflectionMethod Object ( [name] => __construct [class] => Demo ) 獲取參數(shù)getParameters:ReflectionParameter Object ( [name] => id ) 獲取參數(shù)getParameters:ReflectionParameter Object ( [name] => name ) 獲取參數(shù)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 ) )
登錄后復(fù)制
demo里面就有使用了ReflectionClass類(lèi),當(dāng)然ReflectionClass類(lèi)不止于這些方法。