Why This Happens
When declare(strict_types=1) is set at the top of a file, PHP enforces exact type matching for function arguments and return values. Without it, PHP silently coerces '42' to integer 42. With strict types, the string '42' is not accepted where an int is required.
The Problem
<?php
declare(strict_types=1);
function add(int $a, int $b): int {
return $a + $b;
}
$result = add('5', '3'); // TypeError: string given, int expectedThe Fix
<?php
declare(strict_types=1);
function add(int $a, int $b): int {
return $a + $b;
}
$a = (int) $_GET['a']; // Explicit cast
$b = (int) $_GET['b'];
$result = add($a, $b);Step-by-Step Fix
- 1
Check strict_types declaration
Look at the top of the file for declare(strict_types=1). This enables strict type checking for that file's function calls.
- 2
Cast values explicitly
Cast variables to the correct type before passing them: (int), (float), (string), (bool), (array).
- 3
Validate input types
For user input that is always a string, validate and cast to the required type early in your processing pipeline.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free