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

后端 未结 8 562
面向向阳花
面向向阳花 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.

提交回复
热议问题