The declare(strict_types=1); directive makes PHP check the exact types of values passed to functions. This helps catch mistakes early and keeps your code safer.
0
0
Declare strict_types directive in PHP
Introduction
When you want to make sure functions only get the exact type of data they expect.
When working on a team project to avoid confusion about what types are allowed.
When you want to find bugs caused by wrong data types quickly.
When writing code that needs to be very reliable and predictable.
When learning PHP and wanting to understand how types work clearly.
Syntax
PHP
<?php declare(strict_types=1); // Your PHP code here
This directive must be the very first statement in the PHP file, before any other code or whitespace.
It only affects type checking for function calls in the same file.
Examples
This example uses strict types so
add only accepts integers exactly.PHP
<?php declare(strict_types=1); function add(int $a, int $b): int { return $a + $b; } echo add(5, 10);
Without
declare(strict_types=1);, PHP converts "10" to 10 automatically.PHP
<?php function add(int $a, int $b): int { return $a + $b; } // Without strict_types, this works: echo add(5, "10");
Sample Program
This program multiplies two numbers. Because of strict types, both must be floats exactly. The commented line shows what happens if types are wrong.
PHP
<?php declare(strict_types=1); function multiply(float $x, float $y): float { return $x * $y; } // Correct types echo multiply(2.5, 4.0) . "\n"; // Incorrect type - this will cause a TypeError // echo multiply(2, "3");
OutputSuccess
Important Notes
If you forget to put declare(strict_types=1); at the top, PHP will not check types strictly.
Strict types only affect scalar types like int, float, string, and bool.
Type errors caused by strict types help you find bugs early.
Summary
declare(strict_types=1); makes PHP check exact types for function calls.
Put it at the very top of your PHP file before any code.
It helps catch bugs and makes your code safer and clearer.