PHP 8.3.0 RC 6 available for testing

ReflectionProperty::getDefaultValue

(PHP 8)

ReflectionProperty::getDefaultValueReturns the default value declared for a property

说明

public ReflectionProperty::getDefaultValue(): mixed

Gets the implicit or explicitly declared default value for a property.

参数

此函数没有参数。

返回值

The default value if the property has any default value (including null). If there is no default value, then null is returned. It is not possible to differentiate between a null default value and an unitialized typed property. Use ReflectionProperty::hasDefaultValue() to detect the difference.

示例

示例 #1 ReflectionProperty::getDefaultValue() example

<?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
10
rwalker dot php at gmail dot com
2 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