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;
}
As of PHP 8+, you may use union types:
function test(): FailObject|SuccessObject {}
The standard 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 unikn 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
.