Optional Params At End

ID

php.optional_params_at_end

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Php

Tags

api-design, reliability

Description

Reports function signatures in which a parameter that has a default value is declared before a parameter that has none. Optional parameters should come last so that callers can omit them.

Rationale

When a required parameter follows an optional one, the default value can never be used: any caller that needs to supply the trailing required argument must also repeat a value for the earlier optional parameter, which makes the default pointless and the signature misleading. PHP emits a deprecation notice for this pattern. Placing every optional parameter at the end keeps the call site clean and the intent clear. A variadic parameter (…​$rest) is always trailing and legitimately follows an optional parameter, so it is not reported.

<?php
function bad($a, $b = 1, $c)    // FLAW — optional $b precedes required $c
{
    return $a + $b + $c;
}

function good($a, $b, $c = 1)   // OK — the optional parameter is last
{
    return $a + $b + $c;
}

Remediation

Reorder the signature so that every parameter with a default value comes after all required parameters. If reordering would break callers, give the trailing parameters sensible defaults of their own so they too become optional.