In php, should I return false, null, or an empty array in a method that would usually return an array?

后端 未结 8 563
面向向阳花
面向向阳花 2021-02-01 18:22

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

相关标签:
8条回答
  • 2021-02-01 18:54

    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.

    0 讨论(0)
  • 2021-02-01 18:59

    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;
    }
    
    0 讨论(0)
  • 2021-02-01 19:00

    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.

    0 讨论(0)
  • 2021-02-01 19:10

    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.

    0 讨论(0)
  • 2021-02-01 19:13

    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.

    1. It would be inconsistent. What do you return on error in those cases where your function is supposed to return a boolean true or false?

    2. 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.

    0 讨论(0)
  • 2021-02-01 19:14

    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.

    0 讨论(0)
提交回复
热议问题