DEV3 Technologies home

DEV3 Developer Forum

What does declare(strict_types=1) do and should I use it?

PHP helpSolved0 views
dev3 ·

I see declare(strict_types=1); at the top of modern PHP files. What does it change, does it apply across files, and does it break existing code if I add it?

#php#php-8#types

0

1 reply

dev3 · Accepted answer

By default PHP uses coercive typing for scalar types: passing "5" to an int parameter silently converts it. With declare(strict_types=1); PHP throws a TypeError instead.

<?php
declare(strict_types=1);

function addTax(float $price): float { return $price * 1.18; }

addTax(100);      // OK: int to float widening is always allowed
addTax("100");    // TypeError in strict mode, 118.0 without it

Scope: it must be the very first statement in the file and applies to calls made from that file (and return values of functions defined in it), not to the file that defines the function. So a library in strict mode can still be called loosely from a non-strict file.

What it affects

  • Scalar parameter types: int, float, string, bool.
  • Return types of functions defined in the file.
  • Built-in function arguments called from this file: strlen(123) throws in strict mode.

It does not affect == comparisons, array keys or string interpolation.

Adding it to an old codebase

Expect TypeErrors from form values (always strings), database results (PDO may return strings, depending on driver settings) and null passed to non-nullable parameters. Fix at the boundaries:

$qty = (int) ($_POST['qty'] ?? 0);

Roll out file by file, run tests, and use PHPStan to find mismatches ahead of time.

Type features worth using with it

  • Union types int|string (8.0), nullable ?int, mixed, never, static.
  • readonly properties (8.1) and readonly classes (8.2).
  • Constructor property promotion:
final class Money
{
    public function __construct(
        public readonly int $amount,
        public readonly string $currency = 'USD',
    ) {}
}

Recommendation: yes, use strict types in new code and add type declarations to every parameter and return. It catches bugs at the call site instead of days later in a report, and it makes static analysis far more useful.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.