PHP is already strictly typed

Once you use the right tools for the job, you can achieve a type safe system.

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.

Avatar
Gert de Pagter
Software Engineer

My interests include software development, math and magic.