搜尋
首頁後端開發php教程php Reflection反射機制實例詳解
php Reflection反射機制實例詳解Jul 01, 2017 am 10:44 AM
phpreflection詳解

PHP5新增了一項新的功能:Reflection。這個功能使得程式設計師可以

reverse-engineer[逆向工程] class, interface,function,method and extension[擴充庫支援]。

透過PHP程式碼,就可以得到某object的所有訊息,並且可以和它互動。

如假設以下Person類別:

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;
    }
}

透過ReflectionClass,我們可以得到Person類別的以下資訊:

  • 常數Contants

  • #屬性Property Names

  • 方法Method Names

  • #靜態屬性Static Properties

  • 命名空間 Namespace

  • Person類別是否為final或abstract

只要把類別名稱"Person"傳遞給ReflectionClass就可以了:

 $class = new ReflectionClass('Person');

* 取得屬性(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()可以得到屬性名,透過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

有點不可思議了吧。竟然連註解都可以取到。

* 取得方法(methods):透過getMethods() 來取得到類別的所有methods。傳回的是ReflectionMethod物件的陣列

不再示範。

* 最後,透過ReflectionMethod呼叫類別裡面的method。


$data = array("id" => 1, "name" => "Chris", "biography" => "I am am a PHP developer");
foreach($data as $key => $value) {
    if(!$class->hasProperty($key)) {
        throw new Exception($key." is not a valid property");
    }
 
    if(!$class->hasMethod("get".ucfirst($key))) {
        throw new Exception($key." is missing a getter");
    }
 
    if(!$class->hasMethod("set".ucfirst($key))) {
        throw new Exception($key." is missing a setter");
    }
 
    // Make a new object to interact with
    $object = new Person();
 
    // Get the getter method and invoke it with the value in our data array
    $setter = $class->getMethod("set".ucfirst($key));
    $ok = $setter->invoke($object, $value);
 
    // Get the setter method and invoke it
    $setter = $class->getMethod("get".ucfirst($key));
    $objValue = $setter->invoke($object);
 
    // Now compare
    if($value == $objValue) {
        echo "Getter or Setter has modified the data.\n";
    } else {
        echo "Getter and Setter does not modify the data.\n";
   }
}

 

以上是php Reflection反射機制實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

怎样剖析CLDAP协议 Reflection DDoS怎样剖析CLDAP协议 Reflection DDoSMay 22, 2023 pm 01:13 PM

前言2018年上半年,得益于Memcache近5万的反射放大倍数,DDoS的峰值流量已经达到了一个前所未有的新高度—1.7Tbps,这也使得MemcacheReDDoS成为目前DDoS的中坚力量。而与MemcacheReDDoS相比,2016年Akamai曝光的CLDAPReDDoS虽然没有前者极高的效率,但是其56~70倍的放大倍数在DDoS家族中也依然是一名佼佼者,因此也应引起关注。一、CLDAP协议缺陷轻量目录访问协议(LDAP)被定义在RFC2251(LDAPv3)中,由于LDAP是以T

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前By尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具