← BACK
PHP / Syntax

Enforce Strict Typing Across PHP Classes and Methods

Punyapal Shah • • 1 min read
edit this tip →

Declare declare(strict_types=1); at the top of PHP files to prevent unexpected scalar type coercions.

By default, PHP coerces types scalar values (e.g. string '1' to int 1). Adding declare(strict_types=1); enforces strict type constraints on function arguments and return values.

<?php

declare(strict_types=1);

namespace App\Services;

class TaxCalculator
{
    public function calculate(int $amount, float $rate): float
    {
        return $amount * $rate;
    }
}
  • Prevents silent scalar type coercions (like string to integer conversion)
  • Must be declared at the absolute top of PHP files before code execution
  • Helps static analysis tools like PHPStan catch type bugs early

Related Tips

View all tips →

// Got a tip in mind? Contributions are always welcome