PHP:ReflectionParameter,isOptional vs isDefaultValueAvailable

LNT*_*LNT 8 php reflection

两者有什么区别.这两者都以完全相同的方式工作.

public static function getArgsArray($reflectionMethod,$argArray){
    $arr = array();
    foreach($reflectionMethod->getParameters() as $key => $val){
        $arr[$val->getName()] = isset($argArray[$val->getName()]) ?
        $argArray[$val->getName()] : (isset($_REQUEST[$val->getName()])
                ? $_REQUEST[$val->getName()] : ($val->*isDefaultValueAvailable()*  ? $val->getDefaultValue() : NULL));
    }
    return $arr;
}
Run Code Online (Sandbox Code Playgroud)

Phi*_*hil 9

好问题.考虑这个例子

function foo($foo = 'foo', $bar) {}
Run Code Online (Sandbox Code Playgroud)

对于$foo参数,isDefaultValueAvailable()可以理解返回true但是isOptional()会返回,false因为下一个参数($bar)没有默认值,因此不是可选的.要支持非可选$bar参数,$foo必须本身不是可选的.

希望这是有道理的;)

我注意到PHP版本的行为不同.5.5返回上面的内容,而5.4表示参数1既不是可选的,也没有默认值.


Zhu*_*ukV 6

该函数isDefaultValueAvailable只能作用于用户定义的函数,不能作用于系统函数(PHP 核心)。

因此,例如:

class Foo
{
    public function foo($var = null)
    {
    }
}

// Get the "var" argument in method Foo::foo
$refParameter = (new ReflectionClass('Foo'))->getMethod('foo')->getParameters()[0];

print "User function Foo::foo:\n\n";

print 'Optional: ' . ($refParameter->isOptional() ? 'true' : 'false') . "\n";
print 'Default available: ' . ($refParameter->isDefaultValueAvailable() ? 'true' : 'false') . "\n";
if ($refParameter->isDefaultValueAvailable()) {
    print 'Default value: ' . var_export($refParameter->getDefaultValue(), 1);
}

print "\n\n";

print "System function substr\n\n";

// Get the "length" parameter from function substr
$refParameter = (new \ReflectionFunction('substr'))->getParameters()[2];

print 'Optional: ' . ($refParameter->isOptional() ? 'true' : 'false') . "\n";
print 'Default available: ' . ($refParameter->isDefaultValueAvailable() ? 'true' : 'false') . "\n";
if ($refParameter->isDefaultValueAvailable()) {
    print 'Default value: ' . var_export($refParameter->getDefaultValue(), 1);
}

print "\n\n";
Run Code Online (Sandbox Code Playgroud)

并且,此代码显示:您只能从用户定义的函数中获取默认值,而不能从系统函数中获取(substr例如)。但是在用户定义函数和系统函数中isOptional返回的方法true

结论:

  • 如果你想检查参数是可选的,你必须使用isOptional 方法。
  • 您只能从用户定义的函数中获取默认值。
  • 您不能isDefaultValueAvailable在系统 (PHP) 定义的函数上使用方法。

来源:https : //github.com/php/php-src/blob/ccf863c8ce7e746948fb060d515960492c41ed27/ext/reflection/php_reflection.c#L2536-L2573