PHP is already strictly typed

Aug 16, 2019·
Gert de Pagter
Gert de Pagter
· 2 min read

PHP is already strictly typed, in the same way that JavaScript is. Not through the language itself, but with the help of tooling.

JavaScript achieves this through tools like Typescript. (I use typescript as an example, as that is what i normally use.) Typescript adds a lot of new syntax to tha language, which allows for type checking. The transpiler then simply won’t transpile if there are type errors( depending on your configuration). Your code doesn’t do these checks during runtime, so technically you could still create errors by not using the transpiler and writing the JS code directly.

PHP achieves its strict typing through tools like psalm and phpstan. For PHP this doesn’t mean new syntax and code being transpiled however. Since for PHP transpiling the code isn’t something that is done often. There are tools for it, but its generally not that popular. However, PHP devs do love their annotations. A doc comment with @var Foo\Bar here, another one with @return string there and so on. With previously mentioned tooling we can have additional annotations. We can even have @template annotations to get generics.

Just like typescript, there is no run time validation, and because the code isn’t transpiled either, there is no way to stop someone from writing bad code. The only way to stop this is to make the success of these tools mandatory. This means running them in CI, and not allowing a merge to happen unless these tools run successfully.

We don’t need a new language/dialect like P++, we can already increase type safety by using the tooling created for that. So if you want more type safety in your code, and find errors before running the code, use these tools that are already available. If you don’t want to use these tools, then you don’t have to. And i think that is the PHP way.

Gert de Pagter
Software Engineer
My interests include software development and math.