PHP Strict Types
Strict scalar handling helps reveal a wrong type at a call site. It does not turn PHP into a system where every operation is free of coercion.
How it works
declare(strict_types=1) applies per file to scalar calls made from that file. PHP still has operator conversions, and integer-to-float acceptance has its own rule. Use union or nullable types only when the operation genuinely supports those alternatives. Validate request strings first instead of depending on a TypeError to serve as a friendly form parser. A TypeError can also indicate a programming mistake that should be fixed, not silently ignored.
Run it locally
Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.
php -l strict-types.php
php strict-types.phpDownload this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.
Example
<?php
declare(strict_types=1);
function twice(int $value): int { return $value * 2; }
echo twice(3), "\n";
try { twice("3"); } catch (TypeError $error) { echo "Wrong scalar type\n"; }
Expected result
6
Wrong scalar typeThe integer call succeeds. The numeric-looking string is still the wrong argument type at this strict call site. The catch exists to demonstrate the boundary; a maintained request handler should validate the field before calling twice and avoid presenting internal type details to the visitor.
Check the official PHP manual for detailed version and API contracts.