PHP

⚡ Strict Types in PHP (declare(strict_types=1))

By default, PHP is a dynamically and weakly typed programming language that attempts to automatically coerce data types when mismatched values are passed into functions or returned from them. Introducing declare(strict_types=1); enforces strict type checking rules, preventing implicit type coercion and throwing a TypeError whenever types do not match expectations.

  • Crucial Rule: The directive declare(strict_types=1); must be the very first statement in the PHP file (right after the opening <?php tag). Placing it anywhere else triggers a compile error.

🛠️ Weak Typing vs. Strict Typing Comparison

1️⃣ Weak Typing (Default Behavior)
Without strict types, PHP automatically converts string numbers into integers or floats if a function demands a numeric type.

PHP
<?php
// Default mode: Automatic coercion is active
function sum(int $a, int $b): int {
    return $a + $b;
}

// PHP automatically converts "5" string into integer 5
echo sum(5, "10"); // Outputs: 15

2️⃣ Strict Typing (With declare(strict_types=1))
When strict mode is enabled, passing a data type that does not strictly match the type declaration results in an immediate TypeError exception.

PHP
<?php
declare(strict_types=1);

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

// Passing string "10" triggers a Fatal TypeError
try {
    echo sum(5, "10");
} catch (TypeError $e) {
    echo "Error: " . $e->getMessage();
    // Output: Argument #2 ($b) must be of type int, string given
}

🎯 Scope and File-Level Isolation

The strict types directive applies per-file basis for function calls made within that file. It does not affect functions called in other included files unless those files also explicitly declare strict mode at the top.

PHP
<?php
declare(strict_types=1);

function calculateTax(float $amount, float $rate): float {
    return $amount * $rate;
}

// Correct usage: both arguments and return type match declared float types strictly
$tax = calculateTax(100.0, 0.18);
echo "Tax: " . $tax; // Outputs: Tax: 18

  • 📝 Key Advantages of Strict Types

  • Prevents Unexpected Bugs: Stops silent data type conversions that cause unpredictable calculations or logic issues.
  • Improves Code Quality & IDE Auto-completion: Provides clear contracts for parameters and return types, making large-scale codebases easier to maintain and refactor.
  • Exception to Rule: An int value can still be passed into a function requiring a float parameter under strict mode without throwing an error.