1

Just a curiosity, as I was working on a method that expects an instance of an object that implements two unrelated interfaces, I thought:

"wouldn't it be nice to be able to type hint multiple types"...

In PHP you can type hint:

public function foo(InterfaceA $param): bool {}

When dealing with a class that implements more than one interface I think it would be cool to be able to type hint for all possible types/interfaces/etc, something like:

public function foo(InterfaceA | InterfaceB | InterfaceC $param) : bool {}

or even:

public function foo(int | bool $param) : bool {}

or:

public function foo(array | \SplObjectStorage $param) : array {}

I'm sure there is a obvious reason this is not possible, but it's not clear to me and I would appreciate if someone who understands PHP's design better could explain why...? Thank you in advanced :)

  • PHP's design is somewhat the result of growing pains. There were no objects in PHP originally, and then they were added later. The result is the current type/typeless mixture that doesn't really make sense or have any real rhyme or reason to it other than a particular feature just wasn't added for some reason, any reason, or even no reason. –  Jul 08 '19 at 17:59
  • What sort of answer are you expecting outside of "it's not currently supported"? If you want to improve PHP then check out the [source code](https://github.com/php/php-src) and propose an [RFC](https://wiki.php.net/rfc/howto). I can agree with you day and night that this would be nice but I doubt PHP maintainers are browsing Stack Overflow for feature suggestions. – MonkeyZeus Jul 08 '19 at 18:07
  • If you are willing to implement this yourself in PHP code then check out my answer about reflection. https://stackoverflow.com/a/56811963/2191572 – MonkeyZeus Jul 08 '19 at 18:08
  • 2
    Possible duplicate of [php type hinting Can I allow two types?](https://stackoverflow.com/questions/46775489/php-type-hinting-can-i-allow-two-types) – MonkeyZeus Jul 08 '19 at 18:12
  • Thank you for your answers, it was more of a curiosity than anything else. Sometimes I have "what if it could...? or why does it do/not do...?" moments when coding, and I like to understand the reasons and history behind the design decisions of the PHP maintainers. : ) – Sevi Foreman Jul 08 '19 at 19:30
  • Unfortunately this is a case of that feature simply being voted against in [RFC: Union Types](https://wiki.php.net/rfc/union_types) and I cannot find any public discussion of why any single voter voted the way that they did. You can try contacting some of the people that shot it down or check out more discussion/opinion-friendly forums such as https://www.reddit.com/r/PHP/comments/4o2zyg/union_types_rfc_in_voting/ – MonkeyZeus Jul 08 '19 at 19:36

0 Answers0