I've seen tons of threads about what to return in case a PHP function fails. But they were all about PHP 4.
Now in my most recent (PHP 5) project, I want to enforce some sort of consistency with return types (I don't even know, if it's gonna be worth it down the road). So if the normal return type of a method is an array, what should I return in case the method fails?
- null
- empty array()
- throw an exception instead
In C# I would return null, so should I write PHP constantly thinking what I would do in a strongly typed language? Or does something make more sense in this specific scenario? What are the pros and cons for each of the options?
I would throw an exception on an unrecoverable error.
For example, let's say you have a method like getById($id). It is ok to return null if nothing is found. Now let's say you have another method, delete($id) that will itself call getById($id). In this case, if nothing is found (i.e: getById returned null) an exception should be thrown.
Remember that whenever you report an error with a return value, being a null, empty array or string, or even a integer, you will need to handle this error, probably doing some cleanup somewhere else depending on the returned value. This might lead to some dirty in all the methods/functions involved.
Using exceptions will allow you to handle and catch these errors at one place only (at the catch). So you dont have to replicate the code that checks for the error (was the return an empty array? was the return value 1, 2, or 9?, etc). Besides that, using exceptions lets you easily "catalog" the kind of error (like a business logic exception, or an invalid arguments) without writing a lot of if's along the source.
So if a function/method returns something (i.e: it terminated normally), the return value is something you can use (an empty array, a null, or empty string, are all valid return values). If a function/method throws an exception, clearly something went wrong.
Another important thing is that null can be equals to false, 0, and an empty string if you dont use strict checking (=== vs. ==) so this might lead to other kind of bugs. This is where exceptions can also be an advantage.
And of course, whatever you decide, the important thing is to be consistent with your choices along the code.