With PHP 7 you can choose to write much more type-safe code than before, thanks to scalar type hints and return types.
function repeat(string $text, int $times) : string;
But what about arrays? There’s still only the generic “array” type hint, you cannot specify what’s in the array. For the IDE, you can add PhpDoc comments:
/** * @return User */ function allUsers() : array;
Now IDEs like PhpStorm can help with code completion for items in the returned array. But we cannot benefit from any checks at runtime, like with real type hints.
For arguments, there is a partial workaround, using variadic arguments. Take the following function
/** * @param User $users */ function deleteUsers(array $users);
With variadic arguments we can rewrite it to
function deleteUsers(User ...$users);
Usage also changes, to
deleteUsers(...$users); In this call, the argument
$users will be “unpacked” into single variables, and in the method itself “packed” back into an array
$users. Each item is validated to be of type
$users can also be an iterator, it will be converted to an array.
Unfortunately there is no similar workaround for return types, and it only works for the last argument.
See also: Type hinting in PHP 7 – array of objects
I’ve used this technique a lot in PHP 7 code, but I’ve found another one that’s even better and does not come with the mentioned flaws:
Continue reading “PHP 7: Type-safe Arrays of Objects”