php returning mixed data types - good or bad

后端 未结 7 688
梦谈多话
梦谈多话 2021-02-02 14:34

When returning values in php, is it considered good or bad practice to return mixed data types. I\'m working on a project where I am constantly faced with methods that return a

7条回答
  •  [愿得一人]
    2021-02-02 15:11

    Returning mixed type is bad, at least today in 2013. Boom! The way to go is to split this:

    BAD, mixed return type style:

    function checkResult($data)
    {
        if ($data) {
            ...
            return $stuff;
        } else {
            return false;
        } 
    }
    

    People will need additional logic to work checkRsult(), and they never know exactly what type will return.

    GOOD, clearly fixed return type style:

    Maybe the example is not really good, but it shows the way to go.

    function doesResultExist($data)
    {
        if ($data) {
            return true;
        }
        // default return
        return false;
    }
    
    function getResultData()
    {
        ...
        return $stuff;   
    }
    

提交回复
热议问题