PHP 7.1.18 Released

ReflectionParameter::isDefaultValueAvailable

(PHP 5 >= 5.0.3, PHP 7)

ReflectionParameter::isDefaultValueAvailable检查是否有默认值。

说明

public bool ReflectionParameter::isDefaultValueAvailable ( void )

检查参数是否有默认值。

参数

此函数没有参数。

返回值

如果有默认值返回,TRUE if a default value is available, 否则返回 FALSE

参见

add a note add a note

User Contributed Notes 1 note

up
-6
php at marcyes dot com
6 years ago
A quick gotcha that I wasn't aware of, suppose you have a function definition like this:

<?php
function foo(array $bar = array('baz' => ''),$che){}
?>

And you want to check if $bar has a default value:

<?php
$rfunc
= new ReflectionFunction('foo');
$rparams = $rfunc->getParams();

echo
$rparams[0]->isDefaultValueAvailable() ? 'TRUE' : 'FALSE';
?>

That will echo 'FALSE' because $che has no default value so $bar becomes required and the Reflection interface no long sees $bar's default value of array('baz' => '').

The solution is to give $che a default value also:

<?php
function foo(array $bar = array('baz' => ''),$che = null){}
?>

And then $bar's default value will be visible again.

While I understand why it does this, I still wish there was a way to get the default value without resorting to giving all params after it a default value also.
To Top