Re: Union `&` operator
| From: | Eugene Sidelnyk | Date: | Sat, 07 Nov 2020 15:37:49 +0000 |
| Subject: | Re: Union `&` operator | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-112196@lists.php.net to get a copy of this message | ||
Yes.
And I think it will be good if enforced by language.
On Sat, Nov 7, 2020, 5:33 PM Olle Härstedt <olleharstedt@gmail.com> wrote:
> 2020-11-07 15:12 GMT, Eugene Sidelnyk <zsidelnik@gmail.com>:
> > When you follow ISP, you probably would have a lot of interfaces.
> > Thus, client code may require an object to implement a bunch of
> interfaces
> > depending on functionality needed.
> >
> > Consider class
Bar:
> >
> > ```php
> >
> > interface A {}
> >
> > interface B {}
> >
> > interface C {}
> >
> > interface D {}
> >
> > interface E {}
> >
> > class Bar implements A, B, C, D, E {
> > //
> > }
> > ```
> >
> >
> > And some code, which uses Bar, but depends rather on
> > interfaces, which
> > functionality is actually needed:
> >
> > ```php
> > function foo(A & B & E $object) {
> > // some work
> >
> > var_dump($object);
> > }
> > ```
> >
> > It is currently feasable like this (ugly):
> >
> > ```php
> > function foo(A $object) {
> > (function(B $object) {
> >
> > (function(E $object) {
> >
> > // some work
> >
> > var_dump($object);
> >
> > })($object);
> >
> > })($object);
> > }
> > ```
> >
> > Or like this (more readable, but still):
> >
> > ```php
> > function foo(A | B | E $object) {
> >
> > if (!$object instanceof A) {
> > throw new \RuntimeException();
> > }
> >
> > if (!$object instanceof B) {
> > throw new \RuntimeException();
> > }
> >
> > if (!$object instanceof E) {
> > throw new \RuntimeException();
> > }
> >
> > // some work
> >
> > var_dump($object);
> > }
> > ```
> >
> > Another possible option is to create interface, which combines
> > A, B,
> > E, but in some cases it would lead us to interfaces
> > explosion.
> >
> > This idea proposes to eliminate instanceof checks by
> > introducing &
> > union operator.
> >
>
> You mean intersections? Psalm supports this notation.
>