← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

TypeError — When Type Declarations Throw

php PHP 7.0+ Intermediate

TL;DR

TypeError is thrown when a value passed to a typed parameter or return type doesn't match — strict_types=1 makes this happen at call sites too.

Explanation

In PHP 7+, type declarations throw TypeError when violated. With declare(strict_types=1), PHP enforces types strictly at call sites. Without it, PHP coerces where possible (int '5' → 5). TypeError extends Error (not Exception) — catch it separately or use Throwable. Common triggers: passing string to int parameter with strict_types, returning wrong type, violating union types. PHP 8.1 intersection types and DNF types (PHP 8.2) add more ways to throw TypeError.

Common Misconception

TypeError only happens with strict_types — without it PHP silently coerces, but some coercions are still impossible (object to int) and still throw TypeError.

Why It Matters

TypeErrors surface type contract violations at the boundary rather than deep inside a function, making bugs easier to locate and fix.

Common Mistakes

  • Catching Exception instead of Error or Throwable for TypeError.
  • Not using strict_types=1 — coercion hides bugs.
  • Returning null from a non-nullable return type — use ?Type or add null to union.

Code Examples

✗ Vulnerable
function add(int $a, int $b): int { return $a + $b; }
add('five', 2); // Without strict_types: coercion
// With strict_types=1: TypeError: add(): Argument #1 must be int, string given
✓ Fixed
declare(strict_types=1);
function add(int $a, int $b): int { return $a + $b; }

try {
    add('five', 2);
} catch (\TypeError $e) {
    throw new \InvalidArgumentException('Numeric values required', 0, $e);
}

Added 22 Mar 2026
Views 31
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S 1 ping S 0 pings M 0 pings T 0 pings W 1 ping T 0 pings F 3 pings S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 0 pings F 1 ping S 0 pings S 1 ping M 1 ping T 0 pings W 0 pings T 0 pings F 0 pings S
No pings yet today
No pings yesterday
Amazonbot 8 Perplexity 7 Unknown AI 3 Google 3 ChatGPT 2 SEMrush 2 Ahrefs 1
crawler 23 crawler_json 1 pre-tracking 2
DEV INTEL Tools & Severity
🟡 Medium ⚙ Fix effort: Low
⚡ Quick Fix
Use declare(strict_types=1) at top of file and catch \TypeError separately from \Exception — or catch \Throwable for both.
📦 Applies To
PHP 7.0+ web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
catch (Exception
Auto-detectable: ✓ Yes phpstan psalm
⚠ Related Problems
🤖 AI Agent
Confidence: High False Positives: Low ✗ Manual fix Fix: Low Context: Function Tests: Update
CWE-704 CWE-843

✓ schema.org compliant