就算是類(lèi)成員定義為private也可以在外部訪(fǎng)問(wèn),不用創(chuàng)建類(lèi)的實(shí)例也可以訪(fǎng)問(wèn)類(lèi)的成員和方法。
PHP自5.0版本以后添加了反射機(jī)制,它提供了一套強(qiáng)大的反射API,允許你在PHP運(yùn)行環(huán)境中,訪(fǎng)問(wèn)和使用類(lèi)、方法、屬性、參數(shù)和注釋等,其功能十分強(qiáng)大,經(jīng)常用于高擴(kuò)展的PHP框架,自動(dòng)加載插件,自動(dòng)生成文檔,甚至可以用來(lái)擴(kuò)展PHP語(yǔ)言
由于它是PHP內(nèi)建的oop擴(kuò)展,為語(yǔ)言本身自帶的特性,所以不需要額外添加擴(kuò)展或者配置就可以使用。
PHP反射API會(huì)基于類(lèi),方法,屬性,參數(shù)等維護(hù)相應(yīng)的反射類(lèi),已提供相應(yīng)的調(diào)用API。
訪(fǎng)問(wèn)
假設(shè)定義了一個(gè)類(lèi) User,我們首先需要建立這個(gè)類(lèi)的反射類(lèi)實(shí)例,然后基于這個(gè)實(shí)例可以訪(fǎng)問(wèn) User 中的屬性或者方法。不管類(lèi)中定義的成員權(quán)限聲明是否為public,都可以獲取到。
?php
namespace Extend;
use ReflectionClass;
use Exception;
/**
* 用戶(hù)相關(guān)類(lèi)
* Class User
* @package Extend
*/
class User{
const ROLE = 'Students';
public $username = '';
private $password = '';
public function __construct($username, $password)
{
$this->username = $username;
$this->password = $password;
}
/**
* 獲取用戶(hù)名
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* 設(shè)置用戶(hù)名
* @param string $username
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* 獲取密碼
* @return string
*/
private function getPassword()
{
return $this->password;
}
/**
* 設(shè)置密碼
* @param string $password
*/
private function setPassowrd($password)
{
$this->password = $password;
}
}
$class = new ReflectionClass('Extend\User'); // 將類(lèi)名User作為參數(shù),即可建立User類(lèi)的反射類(lèi)
$properties = $class->getProperties(); // 獲取User類(lèi)的所有屬性,返回ReflectionProperty的數(shù)組
$property = $class->getProperty('password'); // 獲取User類(lèi)的password屬性ReflectionProperty
$methods = $class->getMethods(); // 獲取User類(lèi)的所有方法,返回ReflectionMethod數(shù)組
$method = $class->getMethod('getUsername'); // 獲取User類(lèi)的getUsername方法的ReflectionMethod
$constants = $class->getConstants(); // 獲取所有常量,返回常量定義數(shù)組
$constant = $class->getConstant('ROLE'); // 獲取ROLE常量
$namespace = $class->getNamespaceName(); // 獲取類(lèi)的命名空間
$comment_class = $class->getDocComment(); // 獲取User類(lèi)的注釋文檔,即定義在類(lèi)之前的注釋
$comment_method = $class->getMethod('getUsername')->getDocComment(); // 獲取User類(lèi)中g(shù)etUsername方法的注釋文檔
注意:創(chuàng)建反射類(lèi)時(shí)傳送的類(lèi)名,必須包含完整的命名空間,即使使用了 use 關(guān)鍵字。否則找不到類(lèi)名會(huì)拋出異常。
以上就是php提供了什么來(lái)實(shí)現(xiàn)反射的詳細(xì)內(nèi)容,感謝大家的學(xué)習(xí)和對(duì)腳本之家的支持。
您可能感興趣的文章:- PHP的反射動(dòng)態(tài)獲取類(lèi)方法、屬性、參數(shù)操作示例
- php面試實(shí)現(xiàn)反射注入的詳細(xì)方法
- PHP反射原理與用法深入分析
- PHP進(jìn)階學(xué)習(xí)之反射基本概念與用法分析
- php反射學(xué)習(xí)之不用new方法實(shí)例化類(lèi)操作示例
- PHP反射學(xué)習(xí)入門(mén)示例
- PHP反射實(shí)際應(yīng)用示例
- 用PHP的反射實(shí)現(xiàn)委托模式的講解
- 淺析PHP類(lèi)的反射來(lái)實(shí)現(xiàn)依賴(lài)注入過(guò)程
- PHP基于反射機(jī)制實(shí)現(xiàn)自動(dòng)依賴(lài)注入的方法詳解
- PHP基于反射獲取一個(gè)類(lèi)中所有的方法
- PHP反射基礎(chǔ)知識(shí)回顧