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

后端 未结 8 564
面向向阳花
面向向阳花 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 19:15

    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.

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

    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.

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