Home >Backend Development >PHP Tutorial >Why Does PHP 8.0 Throw 'Required Parameter $xxx Follows Optional Parameter $yyy'?
PHP Error: "Required Parameter $xxx Follows Optional Parameter $yyy"
When upgrading to PHP 8.0, developers may encounter a deprecation error stating that a required parameter follows an optional parameter. This error arises from the incorrect usage of default values for required function parameters.
Problem Description:
Previously, in PHP versions before 8.0, functions could be declared with a mix of required and optional parameters by assigning default values to required parameters. However, this practice has been deprecated due to its inherent flaws.
For example, consider the following PHP code:
function test_function(int $var1 = 2, int $var2) { return $var1 / $var2; }
In this code, $var1 is a required parameter with a default value of 2. $var2 is also a required parameter without a default value. This code would work correctly in earlier PHP versions but triggers the deprecation error in PHP 8.0.
New Requirements:
In PHP 8.0 and later, it is now required that required parameters be declared before optional parameters. This change ensures that all required parameters are provided when calling the function, eliminating potential sources of confusion and errors.
Solution:
To resolve the error, simply remove the default value from the earlier required parameter. The code should be rewritten as follows:
function test_function(int $var1, int $var2) { return $var1 / $var2; }
By making this change, the function adheres to the new PHP requirements and will no longer trigger the deprecation error.
The above is the detailed content of Why Does PHP 8.0 Throw 'Required Parameter $xxx Follows Optional Parameter $yyy'?. For more information, please follow other related articles on the PHP Chinese website!