PHP Conference Japan 2024

ReflectionClass::getDefaultProperties

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getDefaultProperties取得預設屬性

說明

public ReflectionClass::getDefaultProperties(): 陣列

從類別(包含繼承的屬性)取得預設屬性。

注意:

此方法用於內建類別時,僅適用於靜態屬性。當此方法用於使用者自定義類別時,無法追蹤靜態類別屬性的預設值。

參數

此函式沒有參數。

回傳值

一個預設屬性的 陣列,鍵是屬性名稱,值是屬性的預設值,如果屬性沒有預設值,則為 null。此函數不區分靜態和非靜態屬性,也不考慮可見性修飾符。

範例

範例 #1 ReflectionClass::getDefaultProperties() 範例

<?php
class Bar {
protected
$inheritedProperty = 'inheritedDefault';
}

class
Foo extends Bar {
public
$property = 'propertyDefault';
private
$privateProperty = 'privatePropertyDefault';
public static
$staticProperty = 'staticProperty';
public
$defaultlessProperty;
}

$reflectionClass = new ReflectionClass('Foo');
var_dump($reflectionClass->getDefaultProperties());
?>

上述範例將輸出:

array(5) {
   ["staticProperty"]=>
   string(14) "staticProperty"
   ["property"]=>
   string(15) "propertyDefault"
   ["privateProperty"]=>
   string(22) "privatePropertyDefault"
   ["defaultlessProperty"]=>
   NULL
   ["inheritedProperty"]=>
   string(16) "inheritedDefault"
}

另請參閱

新增註解

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

articice at ua dot fm
8 年前
runaurufu 的說法並不完全正確,get_class_vars() 不會返回 protected 參數,而這個函數會。

因此,當有一個抽象父類別和在子類別中覆寫 protected 屬性時,它非常有用。
例如,我使用一個類別工廠,其中一個子類別有一些靜態測試方法,仍然需要輸出參數名稱,例如 $this->name 等等。有了這個範例程式碼,可以使用 static::getNotStaticProperty('name'),但不能使用 get_class_vars('name')。

試試看

trait static_reflector {
/*
* 一個純靜態函數,返回同一個類別的非靜態實例的預設屬性
*/
static protected function getNonStaticProperty($key) {
$me = get_class();
$reflectionClass = new \ReflectionClass($me);
$properties_list = $reflectionClass->getDefaultProperties();
if (isset($properties_list[$key]))
return $var_name = $properties_list[$key];
else throw new RuntimeException("錯誤:無法從類別 {$me} 的預設屬性反映非靜態屬性 '{$key}'");
}
}

class a {

use \static_reflector;

protected $key_a = 'test ok';

public static function test() {
echo static::getNonStaticProperty('key_a')."\n";

try {
print static::getNonStaticProperty('key_b');
echo "失敗 沒有拋出例外";
} catch (RuntimeException $e) {
echo "OK ".$e->getMessage();
}

}
}

echo get_class_vars('a')['key_a'];
a::test();

這將會返回
注意:未定義的索引:key_a 於 ...
測試成功
已知錯誤:無法從類別 a 的預設屬性反映非靜態屬性 'key_b'

備註:是的,這是從單元測試複製過來的。
runaurufu AT gmail.com
13 年前
值得注意的是,它不會返回父類別的私有參數...
所以它的運作方式與 get_class_vars 或 get_object_vars 完全相同
To Top