1.2.1441. Wrong Optional Parameter

Wrong placement of optional parameters.

PHP parameters are optional when they defined with a default value, like this :

When a function have both compulsory and optional parameters, the compulsory ones should appear first, and the optional should appear last :

PHP solves this problem at runtime, assign values in the same other, but will miss some of the default values and emits warnings.

It is better to put all the optional parameters at the end of the method’s signature.

Optional parameter wrongly placed are now a Notice in PHP 8.0. The only previous case that is allowed in PHP 8.0 and also in this analysis, is when the null value is used as default for typed arguments.

<?php
    function x($arg = 1) {
        // PHP code here
    }
?>

See also Function arguments.

1.2.1441.1. Suggestions

  • Give default values to all but first parameters. Null is a good default value, as PHP will use it if not told otherwise.

  • Remove default values to all but last parameters. That is probably a weak solution.

  • Change the order of the values, so default-valued parameters are at the end. This will probably have impact on the rest of the code, as the API is changing.

1.2.1441.2. Specs

Short name

Functions/WrongOptionalParameter

Rulesets

All, Analyze, CE, CI-checks, Changed Behavior, CompatibilityPHP80

Exakat since

0.8.4

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Changed Behavior

PHP 8.1 - More

Precision

Very high

Features

parameter, optional-parameter

Examples

FuelCMS, Vanilla

Available in

Entreprise Edition, Community Edition, Exakat Cloud