I've recently been using vs.code with the intelephense extension for PHP development and I've come to appreciate the code navigation and real-time type checking afforded by the IDE when using some of the more advanced type hints.
in T15047: Officially raise minimum required PHP version to 7.2 we updated the minimum required version to PHP 7.2, so presumably regular PHP type hints are ok now.
I've also been experimenting with dynamic PHPDoc-based type hinting extensions introduced in 2019 by PHPStan.org. The functionality seems to have been adopted by at least intelephense and PHPStorm, and perhaps others that I am not aware of.
Well specified type hints enable a capable IDE to provide an experience roughly similar to what can be achieved with TypeScript. That is, structural type specifications which enable intelligent type inference. The type of a function's argument can determine the return type, for example, without specifying a static type.
<?php /** * @template T of SomeType * @param array<T> $things * @return T */ function processThings($things) { foreach ($things as $key => $val) { // pick a thing if ($key == 'some thing') { return $val; } } $thing = reset($things) return $thing; }
The above code tells the IDE that whatever type is contained in the array passed to the function, the same type will be returned, with the type of T constrained to SomeType but otherwise the type is filled in by the context of the call. This is very powerful for providing code documentation as well as real time error hints and suggestions.
PHPStan's website has many better examples of the various things you can do with these type hints. As an experiment, I've gone through a few files in Phorge source and added some type hints and so far the experience is pretty nice.
I guess I'm writing this to gauge how other Phorge contributors feel about introducing these to Phorge source code.