Types are documentation
Adding types to your PHP code base is more than just runtime validation. It helps both developers and static analysis tools, by making the code clearer and easier to understand. Adding types makes code more self-explanatory and gives you a form of documentation.
A function with proper types will help clarify what it is supposed to do. It becomes easier to determine what a function does from reading its signature. Take the following function as an example. Can you figure out what this method does?
function validateUserIsLoggedIn($user);
There are a few ways this function could work. It can return true
or false
, telling you whether the user is logged in. It could
throw an exception if the user is not logged in. It could even return a result object with information. By adding types we know which
case we are dealing with, without having to read the function code:
// Returns whether the user is logged in
function validateUserIsLoggedIn(User $user): bool;
// Will throw an exception if the user is not logged in.
/**
* @throws UserNotLoggedIn
*/
function validateUserIsLoggedIn(User $user): void;
// Will return a result object (or enum)
function validateUserIsLoggedIn(User $user): UserLoginStatus;
By having these types, we know what the method does. If there are multiple ‘versions’ of this method, we can figure out which one is the best for our use case.
But we can do better than just return types. We can specify whether a method expects something has been checked, or if it assumes that already has been done.
For example, do we need to check that name passed to the setUserName
is not empty, or does the method check that itself.
And of course, we get the added benefit, that if we do pass a possibly empty string to setUserName
, then tooling like PHPStan will
tell us that we made a mistake.
class User {
// Do we need to validate before passing, or does the method do that?
public function setUserName(string $name): void;
/**
* @param non-empty-string $name
*/
public function setUserName(string $name): void;
}
By adding a non-empty-string
type to the name, we signal that we are not going to check inside of the method that this
parameter is empty. It also helps us inside of the function, as we now know that it can’t be empty, so we don’t need to ‘deal’
with that edge case.
Ready to take your PHP code to the next level? Start adding types today and see the difference!
If you want to get notified of my next blog post, join the newsletter