Error Proof Your PHP with Type Hints and Return Types
Bug Free PHP with Types
PHP seems to be everyone’s favorite language to criticize and dismiss. Its dismissed as buggy, irrelevant and overall a terrible choice. However PHP still powers a large percentage of the web. WordPress, the most used CMS platform is powered by PHP. A large portion of Facebook is also built with PHP.
Despite the frequent Quora questions it is still very relevant. Its also had a ton of updates in the past few years. If you tried to learn PHP back in 2002 and hated it I would encourage you to give it another chance. It is possible to create well designed, maintainable, non-trivial applications with PHP.
It is true that its very easy to write bad PHP. The barrier to entry is low and often developers who are new to the language just start mixing PHP into their HTML. Some popular CMSs even encourage this bad behavior.
For trivial side projects and for those new to the language mixing PHP into HTML isn’t too bad. And truthfully this is a legitimate way to start learning PHP. But if you want to build any non-trivial application mixing PHP into your HTML will lead to heartache. Its messy, sloppy and just plain ugly. Plus it can make life difficult for front-end developers and designers who want to make updates without wading through piles of PHP.
In this article I’m going to address a simple and relatively painless way to make your PHP more resilient and less error prone using type declarations.
Many software developers who are used to working with languages like Java often complain that PHP does not offer any type declarations. But type declarations for complex data types have been around for a while. And with PHP7 we finally got type hints and return types for scalars! So not only can you type class instances, now you can type integers, strings and booleans.
Strong vs. Loosely Typed Languages
Java is the most popular example of a strongly typed programming language. All types must be explicitly declared. If your code does not conform to the declared types it will not compile.
1 + 1 will be 11 instead of 2. Not fun!
So Why Is This Important?
So adding type declarations to your functions does require more keystrokes. But I promise the extra work is worth it.
Eliminates a whole class of tests
I maintain a large Laravel (PHP framework) application which had quite a few tests to check that model methods were returning the expected instances. Since some functionality is only available Eloquent collections I was constantly need to make sure that the expected collection instances were returned. Otherwise I could run into some nasty errors.
Adding return type declarations eliminated the need for all of these tests. Now all of my tests can focus on actual functionality and logic instead of verifying instances of return values.
Adding type declarations makes your code self documenting. You know exactly what a function expects as input and what the expected output will be. This may sound trivial but your teammates and your future self will be grateful.
Prevents hard to track down bugs
Since many type errors result in silent failures debugging can be very painful. The time it takes to add type declarations to your code is nothing compared to the time and misery you are saving down the road.
It forces you to think about what your methods are actually doing.
This is another benefit that may sound trivial but its important to know what your methods are actually doing. Especially if you are using a framework in your development. If you are copy/pasting from your framework’s documentation you probably aren’t thinking the code through.
Adding type declarations will force you to think about what your methods are actually doing. This will help you gain a deeper understanding of your code base.
Bonus: You’ll be able to learn strongly typed languages faster.
If at some point you have to learn Java you will already be in the habit of using type declarations in your code!
How You Can Implement Type Declarations in Your Current Projects
Requires at least PHP7
- If you’re not already using PHP7 you should be.
- Make sure you upgrade in all of your environments. Both local and production. Its a best practice to ensure that all environments are using the same version of PHP.
- You are able to add type declarations in a piecemeal fashion. Don’t feel like you have to update an entire project in one sitting. Just update as you make changes to the project.
No additional build steps.
- by default PHP will try to coerce arguments to the correct type if possible.
- this means that a parameter type hinted to integer will coerce 1.2 to 1.
- if this is not what you want use strict mode to prevent type coercion
takes a little more time
- adding type declarations does take a little more time and effort. but you will save time later when you don’t have to debug nasty errors.
Makes code more rigid
- You will lose the flexibility of using a loosely typed language but most likely it will be worth it.
- There are very few times when you will actually want to use type coercion.
- If you do need type coercion you may want to do some investigating to find a better way to accomplish your task.