Home  >  Q&A  >  body text

Optional parameter $yyy precedes required parameter $xxx

Deprecated: Required parameter $xxx follows optional parameter $yyy in...

Since upgrading to PHP 8.0, this error will be thrown when running the following code:

function test_function(int $var1 = 2, int $var2) {
    return $var1 / $var2;
}

This worked without issue in past versions of PHP.

P粉236743689P粉236743689341 days ago641

reply all(2)I'll reply

  • P粉021553460

    P粉0215534602023-10-19 10:29:39

    Required parameters without default values ​​should come first.

    function test_function(int $xxx, int $yyy = 2)
    {
        return $xxx * $yyy;
    }

    reply
    0
  • P粉427877676

    P粉4278776762023-10-19 00:33:30

    This method of function declaration has been deprecated in PHP 8.0. It never makes sense to write a function like this because all arguments (until the last required one) need to be specified when calling the function. It's also using the Causing confusion ::getNumberOfRequiredParameters" rel="noreferrer">ReflectionFunctionAbstract class to parse functions and methods.

    The new deprecation simply ensures that function signatures follow the common-sense assumption that required parameters that must be present should always be declared before optional parameters.

    This function should be rewritten to remove the default values ​​for earlier parameters. Since the function can never be called without declaring all arguments, this should have no effect on its functionality.

    function test_function(int $var1, int $var2) {
        return $var1 / $var2;
    }
    

    reply
    0
  • Cancelreply