dqsvnsad79721 2017-09-08 23:12
浏览 62
已采纳

php函数返回0或根本没有返回

bit confused about function returns.
if i have a function with no real return needed, do i have to return 0 or return false to have a better code?

function example($time)
{
   echo $time
   //do i need to return 0 here?
};

$foodstore = array('bread','milk','meat','fruits','veges');
$buyer_list = array('bread', 'milk', 'chocolate');
function example($buyer_list , $foodstore)
{
   foeach($buyer_list as $item)
   {
       if(in_array($item, $foodstore)
        {
           return $item
        }
   }
//if i have to return only a specific $item, do i need to return 0 if no $item is specified.
}

function example($filename)
{
  $file = file_get_contents($filename);
...
  file_put_contents($filename, $file);
//do i need to return 0 here?
}
  • 写回答

1条回答 默认 最新

  • dongzhuohan7085 2017-09-08 23:33
    关注

    Just to clarify: For cleaner and more understandable code, you should always return something, if the function is not a void function. You have to ask yourself the question:

    • Why is the function not returning the desired result?
    • What should be returned in an error case?
    • Is it specified, when the function behaves different?
    • How can the caller react, if the result is unexpected.

    For the last point it is necassary, that you can clearly see, what is the error value, for example by explicit add an return null; after your loop.

    A good way to force you to think about your functions is to write Documentation like, PHPDoc

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?