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!
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.
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.
You can return only 1 object in a C function.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With