PHP Conference Japan 2024

ReflectionClass::getStaticProperties

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getStaticProperties取得靜態屬性

說明

public ReflectionClass::getStaticProperties(): 陣列

取得靜態屬性。

參數

此函式沒有參數。

回傳值

靜態屬性,以 陣列 形式返回。

更新日誌

版本 說明
8.3.0 ReflectionClass::getStaticProperties() 的回傳值類型已從 ?array 變更為 陣列

參見

新增註釋

使用者貢獻的註釋 2 則註釋

jlennox @ google mail
14 年前
我需要遞迴合併子類別及其所有父類別的結果,以下是產生的程式碼

<?php
function GetStaticPropertiesRecursive($class) {
$currentClass = $class;
$joinedProperties = array();
do {
$reflection = new ReflectionClass($class);
$staticProperties = $reflection->getStaticProperties();
foreach (
$staticProperties as $name => $value) {
if (
is_array($value)) {
if (isset(
$joinedProperties[$name]))
$joinedProperties[$name] = array_merge($value, $joinedProperties[$name]);
else
$joinedProperties[$name] = $value;
} else {
if (isset(
$joinedProperties[$name]))
$joinedProperties[$name][] = $value;
else
$joinedProperties[$name] = array($value);
}
}
} while (
$class = get_parent_class($class));
return
$joinedProperties;
}

使用此函式:
class
base {
public static
$Test = array("foo1", "foo2");
}
class
sub extends base {
public static
$Test = "sub";
}

print_r(GetStaticPropertiesRecursive("sub"));
?>

輸出結果為
陣列
(
[Test] => 陣列
(
[0] => foo1
[1] => foo2
[2] => sub
)

)

合併規則遵循 array_merge 處理重複鍵值的規則。
joao dot felipe dot c dot b at gmail dot com
8 年前
getStaticProperties 會傳回屬性本身的集合。這與 getProperties(ReflectionProperty::IS_STATIC) 不同,因為後者會傳回 ReflectionProperty 類別的集合。
To Top