PHP

PHP

Made by DeepSource

Parameter with a default value is not last PHP-W1079

Anti-pattern
Major

Parameters having a default value should always come last after the non-default parameters. Default parameters are optional during function calls. This means, if an argument is not provided for the parameter, the default value defined for the parameter would be used.

Declaring default parameters before non-default parameters defies this purpose since in that case, you have to pass a value for it, even if you want to use the default value. This is just because of the non-default values that are defined after them.

Therefore, it is strongly advised to place the default parameters after the non-default ones.

Bad practice

// invalid: $x defined before parameters without default values
function sum($x = 0, $y, $z) {
    return $x + $y + $z;
}

Recommended

Drop the default value and make it mandatory:

function sum($x, $y, $z) {
    return $x + $y + $z;
}

Or, define the parameter with default values at the last:

function sum($y, $z, $x = 0) {
    return $x + $y + $z;
}

Note: While making this refactor, the sequence of the parameters will be changed. Make sure to update the sequence of the parameters according to your refactor everywhere the function/method is being referenced. Failing to do so might break the existing functionality.