Account
Categories

Strict type checking


Strict type checking means it strictly checks the data types.

If you give the declare(strict_type=1) at the start of the program.

Because of this, the program checks the type of every value everywhere.

When you define the function with a data type and its parameters, and when you call the function then it should match otherwise it displays the type error message.

Uses:

  • It prevents data type errors in the program.
  • It ensures accuracy by enforcing strict data types throughout the program.

Syntax:

<?php
declare(strict_types=1); // It enforces the strict type checking.

function addNumbers(int $a, int $b) {
    return $a + $b;
}
?>

Example:

<?php
declare(strict_types=1); // It enforces the strict type checking.

function multiplyNumbers(int $x, int $y) {
    return $x * $y;
}

// Correct usage
echo multiplyNumbers(5, 3); // Works fine, output: 15

// Incorrect usage
echo multiplyNumbers(5, "3"); // TypeError: Argument 2 must be of type int
?>

Output:

15
Incorrect usage:
Fatal error: Uncaught TypeError: multiplyNumbers(): Argument #2 ($y) must be of type int, string given