Sobes.tech
Middle

When have you encountered strict mode in PHP?

sobes.tech AI

Answer from AI

When developing new functionality that requires high data type accuracy. When refactoring existing code to improve its predictability and reduce the likelihood of errors. When integrating with external services or libraries where correct type passing is important.

The strict mode is enabled by the directive declare(strict_types=1); at the beginning of the file. It affects the handling of scalar types (int, float, string, bool) in function arguments and return values.

Without strict mode, PHP performs automatic type coercion, which can lead to unexpected results:

<?php

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

// Without strict_types=1: "1" and 2 will be coerced to numbers, returning 3
echo sum("1", 2);

With declare(strict_types=1);:

<?php

declare(strict_types=1);

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

// With strict_types=1: Will throw a Fatal error due to incorrect argument type
// echo sum("1", 2);

Advantages of using strict mode:

  • Predictability of code: Data types match expectations.
  • Early error detection: Type mismatches lead to errors at runtime, not during implicit coercion.
  • Improved readability: Clearly shows what data types are expected.
  • Easier refactoring: Changes in data types lead to explicit errors rather than hidden bugs.

Disadvantages:

  • May require more effort when writing code, as you need to be mindful of types.
  • Can complicate working with inherited code that actively uses automatic type coercion.

I use strict mode in new code and gradually implement it in existing code during refactoring. This helps build more reliable and maintainable applications.