Required Parameters After Optional Parameters is Deprecated in PHP 8.0

Required Parameters After Optional Parameters is Deprecated in PHP 8.0

PHP allows defining optional parameters in function and method signatures. These parameters have a default value, which can be specified by using an equals (=) sign. If no argument is passed to optional parameter when the default value will be used.

Since PHP 8.0, specifying required parameters after optional parameters is deprecated. It means that the following function signature is deprecated and PHP emits a deprecation warning:

<?php

function run(int $x = 0, int $y): void {}

Example will output:

Deprecated: Required parameter $y follows optional parameter $x in main.php on line 3

To define required parameter after optional parameter doesn't make sense because we need to pass argument to optional parameter in order to pass argument to required parameter.

In the previous example, a deprecation warning can be resolved by removing the default value:

<?php

function run(int $x, int $y): void {}

However, a deprecation warning is not emitted if we define an optional parameter which has type declaration and the default value is null. The following code will not emit a deprecation warning because we specified int as a type and null as a default value:

<?php

function run(int $x = null, int $y): void {}

Since PHP 7.1, we can use nullable types, so it is recommended to use them. The previous example can be rewritten as follows:

<?php

function run(?int $x, int $y): void {}

Note that, PHP emits a deprecation warning if we define an optional parameter with a default value set to null but type declaration is not specified.

<?php

function run($x = null, int $y): void {}

Example will output:

Deprecated: Required parameter $y follows optional parameter $x in main.php on line 3

Leave a Comment

Cancel reply

Your email address will not be published.