Skip to content
sang.id.vn
Go back

Make PHP Enforce Strict Types

Tiếng Việt

PHP by default lets you pass a string where an int is expected, and it’ll quietly convert it for you. Sounds convenient until you spend hours debugging a type-related bug that would’ve been caught immediately with strict types.

What declare(strict_types=1) Does

Drop this at the top of your PHP file and PHP will stop doing automatic type juggling. If a function expects an int and you pass a string, it throws a TypeError right away.

<?php
declare(strict_types=1);

function add(int $a, int $b): int {
    return $a + $b;
}

echo add(2, 3); // 5
echo add('2', 3); // TypeError: Argument 1 passed to add() must be of the type int, string given

Without strict types, that second call would silently convert '2' to 2 and you’d never know something was off. With strict types, it blows up immediately. That’s what you want.

Why Bother

How to Use It


References:


Share this post on:

Previous Post
Configure MySQL for Full-Text Search with Vietnamese
Next Post
Thesis Report Formatting in Word — Part 3: Tips & Shortcuts