PHP Conference Japan 2024

ReflectionProperty::getDefaultValue

(PHP 8)

ReflectionProperty::getDefaultValue返回屬性宣告的預設值

說明

public ReflectionProperty::getDefaultValue(): 混合類型

取得屬性隱式或顯式宣告的預設值。

參數

此函式沒有參數。

傳回值

如果屬性有任何預設值(包含 null),則返回該預設值。如果沒有預設值,則返回 null。無法區分 null 預設值和未初始化的型別屬性。使用 ReflectionProperty::hasDefaultValue() 來檢測差異。

範例

範例 #1 ReflectionProperty::getDefaultValue() 範例

<?php
class Foo {
public
$bar = 1;
public ?
int $baz;
public
int $boing = 0;
public function
__construct(public string $bak = "default") { }
}

$ro = new ReflectionClass(Foo::class);
var_dump($ro->getProperty('bar')->getDefaultValue());
var_dump($ro->getProperty('baz')->getDefaultValue());
var_dump($ro->getProperty('boing')->getDefaultValue());
var_dump($ro->getProperty('bak')->getDefaultValue());
?>

以上範例將輸出:

int(1)
NULL
int(0)
NULL

另請參閱

新增註解

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

rwalker dot php at gmail dot com
3 年前
適用於 PHP 7 的等效程式碼

<?php
$reflectionProperty
= new \ReflectionProperty(Foo::class, 'bar');

//PHP 8:
$defaultValue = $reflectionProperty->getDefaultValue();

//PHP 7:
$defaultValue = $reflectionProperty->getDeclaringClass()->getDefaultProperties()['bar'] ?? null;
?>
To Top