简体   繁体   中英

PHP Best Practice: Using Mixed return types

I understand that this topic was briefly approached here but I hope to understand the general do's and don'ts of using multiple return types in PHP. There seems to be varied opinions about this feature of PHP.

I would tend to agree that, as pointed out in the thread linked above, for errors, using exceptions is probably more suited; But, what about a function returning, say, two types of meaningful values? For example, let's say a function that returns all the lights that are OFF in a house (:) yes, I'm winging it!)

Essentially, this is what I want to convey: If a basic condition is not met and I don't see a point in going forward and computing my list, I return a boolean. Otherwise, go ahead and do so:

    public function getLightsThatAreOff($house) 
    {
        // if $house itself does not have any power, return true 
        // else 
              //compile an array of lights that are off and return then
    }

I would think that the use case mentioned above is a sort of a sweet-spot for multiple return types. In either case, I would appreciate it if someone provides a general set of guidelines on how to determine whether to use this feature or not.

Thanks!

Mixed types are not good, even if documented well. For example, if a method is returning an array, but there is nothing to return, then it should be an empty array, not false or anything else. ie

array()

It really depends on how you intend to use these functions. Even if you're part of a large development team, as long as you document your code effectively, then you should be able to safely return mixed types. If you develop for yourself, then it really doesn't matter, as long as you know how and where to use your functions.

I will say though, from personal experience, that whenever you can alleviate the possibility of an error, you should. Meaning, if the expected return value of a function is an array, you should probably return a blank array instead of a boolean (false). That way, even if someone doesn't read your documentation, the worst that can happen is that when they try to loop through the array, nothing happens, and the script continues. If you can't foresee it causing any issues, I would highly recommend doing it this way instead of simply returning false. I can't even count how many times I've heard "your database class is broken" when I returned false instead of an array of results if the query failed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM