Search code examples
phpreflection

PHP : ReflectionParameter, isOptional vs isDefaultValueAvailable


What is the difference between two. both of these are working exactly in a same way.

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;
}

Solution

  • Good question. Consider this example

    function foo($foo = 'foo', $bar) {}
    

    For the $foo parameter, isDefaultValueAvailable() would understandably return true however isOptional() would return false as the next parameter ($bar) has no default value and is therefore not optional. To support the non-optional $bar parameter, $foo must itself be non-optional.

    Hope this makes sense ;)

    I've noted that behaviour differs across PHP versions. 5.5 returns the above whereas 5.4 says parameter 1 is both not optional and has no default value.

    Demo: https://3v4l.org/qgbh7