在本篇文章裏我們給各位分享了一篇關於php提供實現反射的方法和實例代碼相關內容,有興趣的朋友們參考下。
就算是類成員定義爲private也可以在外部訪問,不用創建類的實例也可以訪問類的成員和方法。
PHP自5.0版本以後添加了反射機制,它提供了一套強大的反射API,允許你在PHP運行環境中,訪問和使用類、方法、屬性、參數和註釋等,其功能十分強大,經常用於高擴展的PHP框架,自動加載插件,自動生成文檔,甚至可以用來擴展PHP語言
由於它是PHP內建的oop擴展,爲語言本身自帶的特性,所以不需要額外添加擴展或者配置就可以使用。
PHP反射API會基於類,方法,屬性,參數等維護相應的反射類,已提供相應的調用API。
訪問
假設定義了一個類 User,我們首先需要建立這個類的反射類實例,然後基於這個實例可以訪問 User 中的屬性或者方法。不管類中定義的成員權限聲明是否爲public,都可以獲取到。
<?php namespace Extend; use ReflectionClass; use Exception; /** * 用戶相關類 * Class User * @package Extend */ class User{ const ROLE = 'Students'; public $username = ''; private $password = ''; public function __construct($username, $password) { $this->username = $username; $this->password = $password; } /** * 獲取用戶名 * @return string */ public function getUsername() { return $this->username; } /** * 設置用戶名 * @param string $username */ public function setUsername($username) { $this->username = $username; } /** * 獲取密碼 * @return string */ private function getPassword() { return $this->password; } /** * 設置密碼 * @param string $password */ private function setPassowrd($password) { $this->password = $password; } } $class = new ReflectionClass('Extend\User'); // 將類名User作爲參數,即可建立User類的反射類 $properties = $class->getProperties(); // 獲取User類的所有屬性,返回ReflectionProperty的數組 $property = $class->getProperty('password'); // 獲取User類的password屬性ReflectionProperty $methods = $class->getMethods(); // 獲取User類的所有方法,返回ReflectionMethod數組 $method = $class->getMethod('getUsername'); // 獲取User類的getUsername方法的ReflectionMethod $constants = $class->getConstants(); // 獲取所有常量,返回常量定義數組 $constant = $class->getConstant('ROLE'); // 獲取ROLE常量 $namespace = $class->getNamespaceName(); // 獲取類的命名空間 $comment_class = $class->getDocComment(); // 獲取User類的註釋文檔,即定義在類之前的註釋 $comment_method = $class->getMethod('getUsername')->getDocComment(); // 獲取User類中getUsername方法的註釋文檔
注意:創建反射類時傳送的類名,必須包含完整的命名空間,即使使用了 use 關鍵字。否則找不到類名會拋出異常。
以上就是php提供了什麼來實現反射的詳細內容,感謝大家的學習和對神馬文庫的支持。