There are a RFC for union-types (https://wiki.php.net/rfc/union_types)
that was declined, but I see that it is a recurring question here
(today, for instance, David Eddy tried to start this discussion again
with the same concept).
Then, I don't know if the problem is the union methodology like
string|int or if it could be useless.
In my mind, I think that is very useful, mainly over scalar types
(string|int, for instance) or when method could support mixed types of
objects. For instance, I have a method called mergeWith($value) that
allows $value to be instanceof array or self. Currently I am solving
this problem by using assert()
, something like assert(is_array($value)
|| $value instanceof self), but I see that is not the best option.
In this case, I suggests to create a super-type that allows to define
a super-type (typedef) or inline super-type (union-types).
class {
typedef MyType (self, array);
public function mergeWith(MyType $value) {
}
}
Or, following the union-types (as inline super-type):
public function mergeWith(types(self, array) $value) {
}
public function anotherMethod(): types(self, array) {
}
--
David Rodrigues