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

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.

Leave a Comment