I have some methods that can return one of two return types. I'm using a framework utilizing MCV so refactoring these few functions in particular is not appealing.
Is it possible to declare the return type returning one or the other and failing on anything else?
function test(): ? { if ($this->condition === false) { return FailObject; } return SucceedObject; }
PHP doesn't support to return multiple values in a function. Inside a function when the first return statement is executed, it will direct control back to the calling function and second return statement will never get executed.
Use of returnA function can not return multiple values, but similar results can be obtained by returning an array.
The purpose of return statement in PHP is to return control of program execution back to the environment from which it was called. Upon returning, execution of expression following the one which invooked other function or module.
As of PHP 8+, you may use union types:
function test(): FailObject|SuccessObject {}
Another way, available in all versions since PHP 4, is for the two objects to share an interface. Example:
interface ReturnInterface {} class FailObject implements ReturnInterface {} class SuccessObject implements ReturnInterface {} function test(): ReturnInterface {}
In this example, ReturnInterface
is empty. Its mere presence supports the needed return type declaration.
You could also use a base, possibly abstract, class.
To me, for this use case, interfaces are more clear and more extensible than union types. For example, if I later want a WarnObject
I need only to define it as extending ReturnInterface
-- rather than going through all signatures and updating them to FailObject|SuccessObject|WarnObject
.
As noted by bishop, there is an RFC for adding multiple return types. However, I thought I'd add that as of PHP7.1 you can now specify a nullable return type like this:
function exampleFunction(string $input) : ?int { // Do something }
So this function would take in a string and by adding the question mark before int you are allowing it to return either null or an integer.
Here's a link to the documentation: http://php.net/manual/en/functions.returning-values.php
And here's a quote from that page explaining the usage: PHP 7.1 allows for void and null return types by preceding the type declaration with a ? — (e.g. function canReturnNullorString(): ?string)
Also, here's another thread that relates to this: Nullable return types in PHP7
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