Home  >  Q&A  >  body text

The optional parameter $xxx after $yyy is required

<p><br /></p> <pre class="brush:none;toolbar:false;">DEPRECATED: Required parameter $xxx follows optional parameter $yyy... </pre> <p>Since upgrading to PHP 8.0, this error is thrown when running the following code: </p> <pre class="brush:php;toolbar:false;">function test_function(int $var1 = 2, int $var2) { return $var1 / $var2; } </pre> <p>In past PHP versions, this was no problem. </p>
P粉764836448P粉764836448402 days ago508

reply all(2)I'll reply

  • P粉616383625

    P粉6163836252023-08-16 14:16:18

    Required parameters without default values ​​should be placed first.

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

    reply
    0
  • P粉451614834

    P粉4516148342023-08-16 09:03:20

    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 argument) need to be specified when calling the function. This also led to confusion because of problems using the ReflectionFunctionAbstract class to analyze functions and methods.

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

    Functions should be rewritten to remove the default values ​​of previous parameters. Since a function is never called without declaring all its parameters, this has no effect on its functionality.

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

    reply
    0
  • Cancelreply