PHP 8.0: Required Parameter Follows Optional Parameter
With the upgrade to PHP 8.0, developers may encounter the following error:
Deprecated: Required parameter $xxx follows optional parameter $yyy in...
This error arises when the declaration of a function includes an optional parameter followed by a required parameter. For instance, the following code would trigger the error:
function test_function(int $var1 = 2, int $var2) { return $var1 / $var2; }
Clarifying Functional Implications
In PHP versions prior to 8.0, such function declarations were allowed. However, they introduced inconsistencies and confusion when analyzing functions and methods using the ReflectionFunctionAbstract class.
The New Requirement
PHP 8.0 enforces a more logical approach by requiring that all required parameters must be declared before any optional parameters.
Recommended Solution
To resolve the error, simply remove default values from optional parameters. Since the function could not be invoked without specifying all parameters anyway, the functionality should remain unaffected:
function test_function(int $var1, int $var2) { return $var1 / $var2; }
The above is the detailed content of PHP 8.0: Why Do Required Parameters Now Need to Precede Optional Ones?. For more information, please follow other related articles on the PHP Chinese website!