ReflectionProperty::hasDefaultValue

(PHP 8)

ReflectionProperty::hasDefaultValueデフォルト値が宣言されているかをチェックする

説明

public ReflectionProperty::hasDefaultValue(): bool

プロパティにデフォルト値が宣言されているかをチェックします。 暗黙の null のデフォルト値も含めてチェックが行われます。 デフォルト値が存在しない型付きプロパティ(または動的なプロパティ)の場合は、false が返されます。

パラメータ

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

戻り値

プロパティが何かしらデフォルト値を持っている場合(nullを含みます)、true を返します。 プロパティにデフォルト値が宣言されていないか、動的なプロパティの場合は、false を返します。

例1 ReflectionProperty::hasDefaultValue() の例

<?php
class Foo {
public
$bar;
public ?
int $baz;
public ?
int $foo = null;
public
int $boing;

public function
__construct()
{
$this->ping = '';
}
}

$ro = new ReflectionObject(new Foo());
var_dump($ro->getProperty('bar')->hasDefaultValue());
var_dump($ro->getProperty('baz')->hasDefaultValue());
var_dump($ro->getProperty('foo')->hasDefaultValue());
var_dump($ro->getProperty('boing')->hasDefaultValue());
var_dump($ro->getProperty('ping')->hasDefaultValue()); // 動的なプロパティ
var_dump($ro->getProperty('pong')->hasDefaultValue()); // 未定義のプロパティ
?>

上の例の出力は以下となります。

bool(true)
bool(false)
bool(true)
bool(false)
bool(false)

Fatal error: Uncaught ReflectionException: Property Foo::$pong does not exist in example.php

参考

add a note

User Contributed Notes 1 note

up
0
vuryss at gmail dot com
1 day ago
It is useful to note that if this is used on a promoted property, which has a default value, it does not work as expected. The default value is related to the constructor parameter, not to the property itself. So for example, if you reflect this property:

<?php
class SomeClass
{
public function
__construct(
public ?
string $property = null,
) {
}
}
?>

The ReflectionProperty::hasDefaultValue will return false.
To Top