1.2.693. Mismatch Type And Default

The argument typehint and its default value don’t match.

The code may lint and load, and even work when the arguments are provided. Though, PHP won’t eventually execute it.

Most of the mismatch problems are caught by PHP at linting time. It displays the following error message : ‘Argument 1 passed to foo() must be of the type integer, string given’.

The default value may be a constant (normal or class constant) : as such, PHP might find its value only at execution time, from another include. As such, PHP doesn’t report anything about the situation at compile time.

The default value may also be a constant scalar expression : since PHP 7, some of the simple operators such as +, -, , %, `* <https://www.php.net/manual/en/language.operators.arithmetic.php>`_, etc. are available to build default values. Among them, the ternary operator and Coalesce. Again, those expression may be only evaluated at execution time, when the value of the constants are known.

PHP reports typehint and default mismatch at compilation time, unless there is a static expression that can’t be resolved within the compiled file : then it is checked only at runtime, leading to a Fatal error.

<?php

// bad definition : the string is actually an integer
const STRING = 3;

function foo(string $s = STRING) {
    echo $s;
}

// works without problem
foo('string');

// Fatal error at compile time
foo();

// Fail only at execution time (missing D), and when default is needed
function foo2(string $s = D ? null : array()) {
    echo $s;
}

?>

See also Type declarations, Wrong Type Returned, Mismatch Type And Default and Wrong Typed Property Default.

1.2.693.1. Suggestions

  • Match the typehint with the default value

  • Do not rely on PHP type juggling to change the type on the fly

1.2.693.2. Specs

Short name

Functions/MismatchTypeAndDefault

Rulesets

All, Analyze, Changed Behavior, LintButWontExec, Typechecks

Exakat since

1.2.9

PHP Version

All

Severity

Critical

Time To Fix

Slow (1 hour)

Precision

Medium

Features

type, default

Note

This issue may lint but will not run

Available in

Entreprise Edition, Exakat Cloud