Psalm: Static Type Analysis for PHP

PHP, like other interpreted languages, is loosely typed. That makes coders familiar with strictly typed languages (C, C++, Java, etc) a bit squeamish, and it’s easy to see why. A bug based on type coercion can remain hidden for a long time until it eventually snaps like a taunted dog.

PHP already has some measure of strict typing with its declare(strict_types=1) declaration, but this is a file-by-file approach, and you can still use this declaration while using Psalm. Psalm, on the other hand, tackles the entire codebase.

Psalm, a PHP package written by Vimeo’s engineers and open sourced, is a static type analysis tool for PHP. There are others, Phan and PHPStan, but Psalm seems really easy to use, can be installed by Composer, is intuitive, and can be configured to be very strict in its analysis, or a little looser to make it easy to get started. Strictness can be set from the most strict (level 1), to the loosest (level 8). The developers of Psalm recommend allowing Psalm to determine the starting level based on an initial analysis of the codebase, then ramping up strictness as you deal with issues at the easier levels.

It was an eye-opening process using Psalm on one of my own projects, starting at the recommended Level 7 and working up to Level 1, but completely do-able. And since using Psalm, and running it as part of testing along with PHPUnit, it’s been easy to continue using it.

Start by installing Psalm:

composer require --dev vimeo/psalm

After installation, initialize to allow Psalm to configure a starting level; it will also generate an initial psalm.xml config file.

vendor/bin/psalm --init

And, finally, run psalm against your codebase:

vendor/bin/psalm

By default, Psalm ignores composer’s vendor folder. You can add other folders to ignore if they are initially problematic; I ignored my Views folder, for example, until I’d handled everything else, then turned it on again for Views to tackle them later.

To be honest, the sea of red on initially running Psalm was a bit daunting, but working up to level 1 with no errors felt good.

Just to be clear, Psalm, like Typescript, can’t convert your final PHP to being strictly typed. But it can enforce strict typing during your coding, so that your final PHP code will at least behave as if it’s strictly typed. Just like Typescript with Javascript.

Psalm can also integrate with your favorite IDE, but I haven’t looked at that yet.

Worth a look if you’re a PHP developer and you yearn for the peace of mind that strict typing brings.