Sobes.tech
Junior — Middle

Is strict variable and function typing mandatory in PHP?

sobes.tech AI

Answer from AI

In PHP, strict typing of variables and functions is not mandatory by default. PHP uses dynamic typing by default, which means that variable types are determined at runtime and can change.

However, starting from PHP 7, you can enable strict typing for a specific file by adding the directive declare(strict_types=1); at the beginning of the file. In this mode, PHP will strictly check the types of function arguments and return values.

Example of enabling strict typing:

<?php
declare(strict_types=1);

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

echo sum(1, 2); // 3
// echo sum(1, "2"); // will cause an error in strict mode

Without this directive, PHP will attempt to automatically convert types, which can lead to unexpected results.

Is strict variable and function typing mandatory in… - sobes.tech