📡 You're offline — showing cached content
New version available!
Quick Access
PHP Beginner

PHP Type Declarations and Strict Mode in PHP 8

Learn PHP type declarations, strict_types, union types, and nullable types.

EzyCoders Admin May 29, 2026 2 min read 6 views
PHP Type Declarations and Strict Mode in PHP 8
Share: Twitter LinkedIn WhatsApp

What is it?

Type declarations let you specify exactly what types a function accepts and returns. strict_types=1 makes PHP enforce them strictly instead of silently converting types.

Why does it matter?

Typed PHP catches bugs at the function boundary before they corrupt data deep in your application. IDEs use types for autocomplete and static analysers like PHPStan use them to find errors before runtime.

Learn PHP type declarations, strict_types, union types, and nullable types.

Real-World Use Cases

  • 🔒 Secure payment processing - Declare amount as float and currency as string — passing a string by mistake causes an immediate TypeError instead of silently charging the wrong amount.
  • 📊 Report generation - Typed return types guarantee that getRevenue() always returns a float — callers can safely do arithmetic on the result.
  • 🧪 Easier testing - Typed parameters make tests self-documenting — you know exactly what to pass without reading the function body.
  • 🏗️ Large team projects - Types act as documentation — new developers know what each function expects without guessing.

Parameter and Return Types

function add(int $a, int $b): int
{
    return $a + $b;
}

strict_types — No Silent Conversions

declare(strict_types=1);

function add(int $a, int $b): int
{
    return $a + $b;
}

add("10", "20"); // TypeError

Nullable and Union Types

function getName(?string $name): ?string
{
    return $name;
}

// Union Type

function display(int|string $value): int|string
{
    return $value;
}

Q: Should I use strict_types in every file?

Yes, in new projects. It prevents silent type coercion bugs. The main benefit: passing wrong types throws a clear TypeError immediately rather than silently producing wrong results.

 

EzyCoders Admin
Written by
EzyCoders Admin

Team Lead and Full-Stack Developer with experience in PHP, JavaScript, SQL, DSA, and System Design. Passionate about software engineering, scalable web technologies, and helping developers prepare for coding interviews and tech careers through practical tutorials and professional guidance.

Comments (0)

No comments yet. Be the first!

Leave a Comment