PHP 8.1.28 Released!

ReflectionProperty::getDefaultValue

(PHP 8)

ReflectionProperty::getDefaultValueプロパティで宣言されたデフォルト値を返す

説明

public ReflectionProperty::getDefaultValue(): mixed

プロパティに明示または黙示的に宣言されているデフォルト値を取得します。

パラメータ

この関数にはパラメータはありません。

戻り値

プロパティに何かしらデフォルト値が存在する場合(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

参考

add a note

User Contributed Notes 1 note

up
11
rwalker dot php at gmail dot com
3 years ago
An equivalent for PHP 7:

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

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

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