问题
I've found several responses to this, but none pertaining to PHP (which is an extremely weak typed language):
With regards to PHP, is it appropriate to return false, null, or an empty array in a method that would usually return an array, but has a failure occur?
In other words, if another developer jumped in on my project, what would they expect to see?
回答1:
An array is a collection of things. An empty array would signal that "everything went fine, there just isn't anything in that collection". If you actually want to signal an error, you should return false
. Since PHP is dynamically typed, it's easy to check the return value either strictly or loosely, depending on what you need:
$result = getCollection();
if (!$result) // $result was false or empty, either way nothing useful
if ($result === false) // an actual error occurred
if ($result) // we have an array with content
There are also exceptions for error reporting in exceptional cases. It really depends on the responsibilities of the function and the severity of errors. If the role of the function allows the response "empty collection" and "nope" equally, the above may be fine. However, if the function by definition must always return a collection (even if that's empty) and in certain circumstances it cannot, throwing an exception may be a lot more appropriate than returning false
.
回答2:
I would strongly discourage to return mixed type return values. I consider it to be so much a problem, that i wrote a small article about not returning mixed typed values.
To answer your question, return an empty array. Below you can find a small example, why returning other values can cause problems:
// This kind of mixed-typed return value (boolean or string),
// can lead to unreliable code!
function precariousCheckEmail($input)
{
if (filter_var($input, FILTER_VALIDATE_EMAIL))
return true;
else
return 'E-Mail address is invalid.';
}
// All this checks will wrongly accept the email as valid!
$result = precariousCheckEmail('nonsense');
if ($result == true)
print('OK'); // -> OK will be given out
if ($result)
print('OK'); // -> OK will be given out
if ($result === false)
print($result);
else
print('OK'); // -> OK will be given out
if ($result == false)
print($result);
else
print('OK'); // -> OK will be given out
Hope this helps preventing some misunderstandings.
回答3:
Just speaking for myself, I normally prefer to return an empty array, because if the function always returns an array, it's safe to use it with PHP's array functions and foreach (they'll accept empty arrays). If you return null or false, then you'll have to check the type of the result before passing it to an array function.
If you need to distinguish between the case where the method executed correctly but didn't find any results, and the case where an error occurred in the method, then that's where exceptions come in. In the former case it's safe to return an empty array. In the latter simply returning an empty array is insufficient to notify you of the fact an error occurred. However if you return something other than an array then you'll have to deal with that in the calling code. Throwing an exception lets you handle errors elsewhere in an appropriate error handler and lets you attach a message and a code to the exception to describe why the failure happened.
The below pseudo-code will simply return an empty array if we don't find anything of interest. However, if something goes wrong when processing the list of things we got back then an exception is thrown.
method getThings () {
$things = array ();
if (get_things_we_are_interested_in ()) {
$things [] = something_else ();
}
if (!empty ($things)) {
if (!process_things ($things)) {
throw new RuntimeExcpetion ('Things went wrong when I tried to process your things for the things!');
}
}
return $things;
}
回答4:
It depends on the situation and how bad the error is, but a good (and often overlooked) option is to throw an exception:
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
else return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
This will ensure that your function will not fail silently and errors won't go unseen.
回答5:
I assume that the return type of your method is array, so you should return an empty array only if the execution went fine but no results were found.
In case of an error, you should throw an exception. This should be the preferred way to handle errors.
回答6:
Here's a modern answer that's been valid since the 1960's probably.
Some bad design choices in the earliest versions of PHP (before PHP 4) have made many PHP developers exposed to conventions that have always been bad. Fortunately, PHP 5 have come and gone - which helped guide many PHP developers on to the "right path".
PHP 7 is now seeing the benefits of having been through the PHP 5 phase - it is one of the fastest performing script languages in existence.
- and this has made it possible to make PHP 7 one of the fastest and most powerful scripting languages in existence.
Since PHP version 4, huge efforts have been made by PHP core developers to gradually improve the PHP language. Many things remain, because we still want to have some backward compatability.
DON'T return false on error
The only time you can return FALSE in case of error, is if your function is named something like
isEverythingFine()
.
false
has always been the wrong value to return for errors. The reason you still see it in PHP documentation, is because of backward compatability.
It would be inconsistent. What do you return on error in those cases where your function is supposed to return a boolean
true
orfalse
?If your function is supposed to return something other than booleans, then you force yourself to write code to handle type checking. Since many people don't do type checking, the PHP opcode compiler is also forced to write opcodes that does type checking as well. You get double type checking!
You may return null
Most scripting languages have made efficient provisions for the null
value in their data types. Ideally, you don't even use that value type - but if you can't throw an exception, then I would prefer null
. It is a valid "value" for all data types in PHP - even if it is not a valid value internally in the PC.
Optimally for the computer/CPU is that the entire value is located in a single 1, 2, 4 or 8 byte memory "cell". These value sizes are common for all native value types.
When values are allowed to be null
, then this must be encoded in a separate memory cell and whenever the computer needs to pass values to a function or return them, it must return two values. One containing isNull
and another for the value.
You may return a special value depending on type
This is not ideal, because
- If your function is supposed to return an integer, then return -1.
- If your function is supposed to return a string
You should throw exceptions
Exceptions match the inner workings of most CPUs. They have a dedicated internal flag to declare that an exceptional event occurred.
It is highly efficient, and even if it wasn't we have gigantic benefits of not having a lot of extra work in the normal non-erroneous situation.
回答7:
If there's really a problem then you should raise an error, otherwise if the criteria aren't met etc then return a blank array.
回答8:
Whichever you prefer, though I suggest an empty array for the for a good reason. You don't have to check the type first!
<?php
function return_empty_array() {
return array();
}
$array = return_empty_array();
// there are no values, thus code within doesn't get executed
foreach($array as $key => $value) {
echo $key . ' => ' . $value . PHP_EOL;
}
?>
In any other case, if you'd return false or null, you'd get an error at the foreach loop.
It's a minuscule difference, though in my opinion a big one. I don't want to check what type of value I got, I want to assume it's an array. If there are no results, then it's an empty array.
Anyway, as far as I'm concerned there are no "defaults" for returning empty values. Native PHP functions keep amazing me with the very different values it returns. Sometimes false, sometimes null, sometimes an empty object.
来源:https://stackoverflow.com/questions/11536128/in-php-should-i-return-false-null-or-an-empty-array-in-a-method-that-would-us