TypeError
PHPERRORCommonType
Argument or return type mismatch
Quick Answer
Enable declare(strict_types=1) and use typed properties to catch type mismatches at call sites.
What this means
Thrown in strict_types=1 mode when a function argument or return value does not match the declared type, or when a built-in function receives an argument of the wrong type.
Why it happens
- 1Passing a string where an int is declared
- 2Returning null from a non-nullable return type
Fix
Add strict_types and union types
Add strict_types and union types
<?php declare(strict_types=1);
function add(int $a, int $b): int {
return $a + $b;
}
// Use int|string for flexible params
function format(int|string $val): string {
return (string) $val;
}Why this works
strict_types=1 makes type declarations strict; union types allow multiple accepted types.
Code examples
Triggerphp
<?php declare(strict_types=1);
function double(int $n): int { return $n * 2; }
double("5"); // TypeErrorNullable typephp
function find(?int $id): ?User {
return $id ? User::find($id) : null;
}Catch TypeErrorphp
try {
setAge("old");
} catch (TypeError $e) {
echo "Type error: " . $e->getMessage();
}Same error in other languages
Sources
Official documentation ↗
PHP Manual
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev