Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 360
user2334532 Avatar asked Apr 30 '13 05:04

user2334532


People also ask

Can PHP function return different types?

Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called.

What is a mixed return type?

mixed is a pseudo type added in PHP 8 that conveys the type of the parameter/return/property can be of any type. mixed type includes all scalar types in PHP, null , all class objects, callable , and even resource . mixed is equivalent to a Union Type of: string|int|float|bool|null|array|object|callable|resource.

Can a function return 2 different types?

You can return only 1 object in a C function.

Why to use return type in PHP?

Return type declaration is specifying the expected data types of the result that a function or a class method should return. Due to return type declaration, PHP, for example, can convert the integer result into a string before returning the result of the function.


1 Answers

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. i.e.

array()
like image 99
Eddie Jaoude Avatar answered Oct 03 '22 06:10

Eddie Jaoude