PHP的反射機制
阿新 • • 發佈:2018-11-10
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
介紹:
PHP5添加了一項新的功能:Reflection。這個功能使得phper可以reverse-engineer class, interface,function,method and extension。通過PHP程式碼,就可以得到某object的所有資訊,並且可以和它互動。
反射是什麼?
它是指在PHP執行狀態中,擴充套件分析PHP程式,匯出或提取出關於類、方法、屬性、引數等的詳細資訊,包括註釋。這種動態獲取的資訊以及動態呼叫物件的方法的功能稱為反射API。反射是操縱面向物件範型中元模型的API,其功能十分強大,可幫助我們構建複雜,可擴充套件的應用。
其用途如:自動載入外掛,自動生成文件,甚至可用來擴充PHP語言。
php反射api由若干類組成,可幫助我們用來訪問程式的元資料或者同相關的註釋互動。藉助反射我們可以獲取諸如類實現了那些方法,建立一個類的例項(不同於用new建立),呼叫一個方法(也不同於常規呼叫),傳遞引數,動態呼叫類的靜態方法。
反射api是php內建的oop技術擴充套件,包括一些類,異常和介面,綜合使用他們可用來幫助我們分析其它類,介面,方法,屬性,方法和擴充套件。這些oop擴充套件被稱為反射。
通過ReflectionClass,我們可以得到Person類的以下資訊:
1)常量 Contants
2)屬性 Property Names
3)方法 Method Names靜態
4)屬性 Static Properties
5)名稱空間 Namespace
6)Person類是否為final或者abstract
例子
class Person { /** * For the sake of demonstration, we"re setting this private */ private $_allowDynamicAttributes = false; /** type=primary_autoincrement */ protected $id = 0; /** type=varchar length=255 null */ protected $name; /** type=text null */ protected $biography; public function getId() { return $this->id; } public function setId($v) { $this->id = $v; } public function getName() { return $this->name; } public function setName($v) { $this->name = $v; } public function getBiography() { return $this->biography; } public function setBiography($v) { $this->biography = $v; }}
接下來反射它,只要把類名"Person"傳遞給ReflectionClass就可以了:
$class = new ReflectionClass('Person');//建立 Person這個類的反射類$instance = $class->newInstanceArgs($args);//相當於例項化Person 類
1)獲取屬性(Properties):
$properties = $class->getProperties();foreach($properties as $property) { echo $property->getName()."\n";}// 輸出:// _allowDynamicAttributes// id// name// biography
預設情況下,ReflectionClass會獲取到所有的屬性,private 和 protected的也可以。如果只想獲取到private屬性,就要額外傳個引數:
$private_properties = $class->getProperties(ReflectionProperty::IS_PRIVATE);
可用引數列表:
ReflectionProperty::IS_STATIC
ReflectionProperty::IS_PUBLIC
ReflectionProperty::IS_PROTECTED
ReflectionProperty::IS_PRIVATE
如果要同時獲取public 和private 屬性,就這樣寫:ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED。
通過$property->getName()可以得到屬性名。
2)獲取註釋:
通過getDocComment可以得到寫給property的註釋。foreach($properties as $property) { if($property->isProtected()) { $docblock = $property->getDocComment(); preg_match('/ type\=([a-z_]*) /', $property->getDocComment(), $matches); echo $matches[1]."\n"; }}// Output:// primary_autoincrement// varchar// text
3)獲取類的方法
獲取方法(methods):通過getMethods() 來獲取到類的所有methods。4)執行類的方法:
$instance->getBiography(); //執行Person 裡的方法getBiography//或者:$ec=$class->getmethod('getName'); //獲取Person 類中的getName方法$ec->invoke($instance); //執行getName 方法