Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to specify multiple return types on PHP 7?

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; } 
like image 783
myol Avatar asked May 04 '16 16:05

myol


People also ask

Can a function have 2 return statements PHP?

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.

Can you return multiple values in PHP?

Use of returnA function can not return multiple values, but similar results can be obtained by returning an array.

What does PHP return?

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.


2 Answers

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.

like image 113
bishop Avatar answered Sep 20 '22 09:09

bishop


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

like image 27
david.lee Avatar answered Sep 20 '22 09:09

david.lee