PHP Strict Types

Why use declare(strict_types=1) ?

Strict typing is commonly used on the top of files php, so using declare(strict_types=1) PHP expects the values with the type matching with the target types.

See the below with out the strict_types:

<?php
 
function sum(int $a, int $b) {
return $a + $b;
}
 
echo sum(2.5, 2.5); //4

Instead of of sum the float values the PHP will convert the float value to integers value. In this example PHP implicitly coerces the values the 2.5 value to 2. Then the sum will works but the php will return the message for each argument below:

Deprecated: Implicit conversion from float 2.5 to int loses precision

Adding the strict type at the beginning of the file like the example below, In the strict mode, PHP expects the values with the type matching with the target types.

<?php
 
declare(strict_types=1);
 
function sum(int $a, int $b) {
return $a + $b;
}
 
echo sum(2.5, 2.5);

When the sum function is executed, will return the error below:

TYPE ERROR sum(): Argument #1 ($a) must be of type int, float given

Strict type declaration can help you catch bugs early on by restricting PHP from automatically casting primitive values. It may be a bit daunting when you start to use it, as you need to properly define everything from the start. Using it may require some adjustment initially, but the benefits of catching errors early make it worthwhile.

Code highlighting provided by Torchlight