Strict types

We do use declare(strict_types=1); by default.

Strict typing applies to function calls made from within the file with strict typing enabled. It helps us to catch some tricky bugs. On another hand, it requires a developer to think more possible variable types, but at the end of the day they have more stable code.

PHP
<?php

declare(strict_types=1);

...

Here's what the declare(strict_types=1); statement does:

  • Enabling Strict Type Checking: By default, PHP has a loose type system, which means that type coercion can occur in certain situations. For example, if you pass an integer to a function that expects a string, PHP will automatically convert the integer to a string. With strict type checking enabled, such type coercion is not allowed, and PHP will throw a TypeError if the types don't match.
  • File-level Scope: The declare(strict_types=1); statement must be the first statement in a PHP file, and it applies strict type checking rules to the entire file. It cannot be used within functions or classes.
  • Scalar Type Hints: When strict type checking is enabled, scalar type hints (int, float, string, bool) must be respected. This means that if a function parameter is type-hinted as int, you cannot pass a non-integer value to that function, or a TypeError will be thrown.
  • Return Type Declarations: With strict type checking enabled, return type declarations in functions and methods must be respected. If a function declares a return type of int, it must return an integer value, or a TypeError will be thrown.
  • No Type Coercion: Strict type checking disables type coercion, which means that if an operation involves values of incompatible types, a TypeError will be thrown instead of coercing the values to compatible types.