ReflectionClass::getProperties()函數(shù)用于獲取類的屬性信息。
函數(shù)簽名: array ReflectionClass::getProperties(int $filter = null)
參數(shù):
- $filter(可選):用于過(guò)濾屬性的參數(shù),可以是以下常量之一:
- ReflectionProperty::IS_STATIC:僅返回靜態(tài)屬性
- ReflectionProperty::IS_PUBLIC:僅返回公共屬性
- ReflectionProperty::IS_PROTECTED:僅返回受保護(hù)的屬性
- ReflectionProperty::IS_PRIVATE:僅返回私有屬性
返回值: 返回一個(gè)ReflectionProperty對(duì)象的數(shù)組,每個(gè)對(duì)象表示一個(gè)屬性。
示例:
class MyClass {
public $publicProperty;
protected $protectedProperty;
private $privateProperty;
static $staticProperty;
}
$reflection = new ReflectionClass('MyClass');
$properties = $reflection->getProperties();
foreach ($properties as $property) {
echo $property->getName() . "\n";
}
輸出:
publicProperty
protectedProperty
privateProperty
staticProperty
在上面的示例中,我們創(chuàng)建了一個(gè)名為MyClass
的類,并定義了不同類型的屬性。然后我們使用ReflectionClass來(lái)獲取該類的屬性信息,并使用foreach循環(huán)遍歷每個(gè)屬性,并通過(guò)ReflectionProperty的getName()方法獲取屬性的名稱并打印出來(lái)。
需要注意的是,如果想獲取特定類型的屬性,可以在getProperties()函數(shù)中傳遞相應(yīng)的過(guò)濾參數(shù)。例如,如果只想獲取靜態(tài)屬性,可以使用$properties = $reflection->getProperties(ReflectionProperty::IS_STATIC);
。