Enable strict typing mode in PHP with declare(strict_types=1). Understand its implications with code examples.

  • @abhibeckert
    link
    1
    edit-2
    8 months ago

    Is it necessary? No. It never was. But it is recommended.

    Consider this code:

    function add(int $a, int $b) { return $a + $b; }
    
    $result = add(5, '10');
    

    In strict_types mode, passing a string will throw an exception. In the default mode (including in PHP 8), the string will be silently cast to an integer.

    Here’s a more realistic example:

    $result = add($_POST['a'], $_POST['b']);
    

    HTTP values are always strings. So that code will only work with strict types disabled… and there is a lot of PHP code in the world that relies on this arguably “bad” behaviour.

    I’d bet one day strict types be enabled by default. So if you want your code to be future proof… get used to enabling it now for all new files. Also I agree with @Dwoncount - you should really be using JSON instead of $_POST. And your JSON should have integer values, not strings.