當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


PHP ReflectionClass getProperties()用法及代碼示例


ReflectionClass::getProperties()函數是PHP中的內置函數,用於返回反射屬性的數組。

用法:

ReflectionClass::getProperties($filter) : array

參數:此函數接受一個參數過濾器,該過濾器有助於除去某些反射的屬性。


返回值:此函數返回反映的屬性的數組。

以下示例程序旨在說明PHP中的ReflectionClass::getProperties()函數:
示例1:

<?php 
  
// Defining a class named as Departments 
class Departments { 
    public $Dept1 = 'CSE'; 
    private $Dept2 = 'ECE'; 
    public static $Dept3 = 'EE'; 
} 
  
// Using ReflectionClass over the class Departments 
$ReflectionClass = new ReflectionClass('Departments'); 
  
// Calling getProperties() function over a filter called  
// ReflectionProperty::IS_PUBLIC which   
// will reflect results of only public properties 
$A = $ReflectionClass->getProperties(ReflectionProperty::IS_PUBLIC); 
  
// Getting an array of the reflected properties 
var_dump($A); 
?>

輸出:

array(2) {
  [0]=>
  object(ReflectionProperty)#2 (2) {
    ["name"]=>
    string(5) "Dept1"
    ["class"]=>
    string(11) "Departments"
  }
  [1]=>
  object(ReflectionProperty)#3 (2) {
    ["name"]=>
    string(5) "Dept3"
    ["class"]=>
    string(11) "Departments"
  }
}

示例2:

<?php 
    
// Defining a class named as Company 
class Company { 
    public $C1; 
    private $C2; 
    public static $C3; 
} 
    
// Using ReflectionClass over the class Company 
$ReflectionClass = new ReflectionClass('Company'); 
    
// Calling getProperties() function without 
// of any filter 
$A = $ReflectionClass->getProperties(); 
    
// Getting an array of the reflected properties 
var_dump($A); 
?>
輸出:
array(3) {
  [0]=>
  object(ReflectionProperty)#2 (2) {
    ["name"]=>
    string(2) "C1"
    ["class"]=>
    string(7) "Company"
  }
  [1]=>
  object(ReflectionProperty)#3 (2) {
    ["name"]=>
    string(2) "C2"
    ["class"]=>
    string(7) "Company"
  }
  [2]=>
  object(ReflectionProperty)#4 (2) {
    ["name"]=>
    string(2) "C3"
    ["class"]=>
    string(7) "Company"
  }
}

參考: https://www.php.net/manual/en/reflectionclass.getproperties.php



相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 PHP | ReflectionClass getProperties() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。