Learn to improve your PHP code in 1 minute by adding strict types.

How to do it

Adding strict types to your code is stupidly easy. Simply just add the line declare(strict_types=1); to the top of every PHP file you write. It must appear above everything in the file except for the opening <?php tag.

What does it do?

Adding strict_types to the top of your PHP file enables strict typing for that file. What does that mean? It means that PHP will disallow type coercion, which essentially means playing fast and loose with your types. For example, let’s look at the following code, first without strict types:

<?php

function addNumbers(int $x, int $y): int
{
    return $x + $y;
}

echo addNumbers('1', '2');

This code executes without complaint and prints out “3”. Even though the function is only supposed to accept integers, PHP will, by default, helpfully coerce the types to makes things work for you. With strict types enabled, it’s a different story:

<?php

declare(strict_types=1);

function addNumbers(int $x, int $y): int
{
    return $x + $y;
}

echo addNumbers('1', '2');

With strict types enabled, we receive a fatal error Uncaught TypeError: addNumbers(): Argument #1 ($x) must be of type int, string given. Hooray!

Why should I use it?

Are we just gluttons for punishment? Do we want to make our jobs tougher? No. But this type of helpful looseness can be the source of rather insidious and difficult to track bugs. Consider the following:

<?php

function addNumbers(int $x, int $y): int
{
    return $x + $y;
}

echo addNumbers(1.9, 1.9);

This code block outputs “2”. Is that what you’d expect from 1.9 + 1.9? Probably not. You’d probably want this to output 3.8, or perhaps 4, but 2 is almost certainly not what you wanted. Now, let’s try it with strict types:

<?php

declare(strict_types=1);

function addNumbers(int $x, int $y): int
{
    return $x + $y;
}

echo addNumbers(1.9, 1.9);

Fatal error: Uncaught TypeError: addNumbers(): Argument #1 ($x) must be of type int, float given.
Ahh yeah, that’s the stuff! In this case, PHP complains about this state of affairs instead of just quietly plugging along with incorrect values. These type of errors should produce logs and make you, the developer, investigate what’s happening and fix it. Which is a lot better than just happily treating 4’s as 2’s.

Mercifully, it doesn’t complain the other way. Floats can accept integers.

<?php

declare(strict_types=1);

function addNumbers(float $x, float $y): float
{
    return $x + $y;
}

echo addNumbers(1, 2);

All good in the hood. This prints “3” with nary a warning.

When should I use it?

Use this on every single new PHP file you create.

Adding strict types to a file will enforce it only for that file. It will not affect any other files, even if other files call functions/classes/methods in the strictly typed file. It only takes effect directly within the strictly typed file. Now that’s what I call encapsulation!

Given that it has benefits and pretty much no drawbacks, you should add it to every single new file. There’s no reason to exclude files like PHPUnit test files either; indeed, strict typing is a great benefit in testing!

However, I would not go so far as to start automatically adding it to every existing file you have. It’s possible that your existing, crummy, legacy code depends on type coercion and the benefits are not really so massive as to blindly take the risk of breaking something. So begin all new files this way and, perhaps, add it to some existing files that are short and sweet enough that you can clearly see there will be no adverse effects.

Other benefits

This is the mark of a professional. Your manager is going to flip his shit when he sees this. In fact, under U.S. law, you are legally entitled to sue your employer if they don’t give you at least a 10% raise for using strict types1. This is leveraging the broken window theory of code in a positive way. When you see this at the top of a PHP file, you know that some care was taken with the contents within. Future developers will want to follow suit and maintain the level of quality contained in a PHP file with strict types.

Conclusion

I hope I have convinced you that adding strict types is easy, has some positive effect, and no negative effect whatsoever. From this point on, you can automatically add this line to every new PHP file you start. You and your codebase will be better for it. You will probably get a raise.



1 Legally, anyone can sue anyone for anything. I make no predictions on your chances of winning the case. Please consult your attorney for all legal counsel.