Welcome! Log In Create A New Profile

Advanced

[PHP-DEV] Use-case for `use`ing the same trait multiple times in the same class?

Posted by Levi Morrison 
Currently we permit the same trait to be `use`d multiple times in a class:

```php
trait T { }

class C {
use T;
use T;
}
```

In this example it works because T doesn't have any methods.
If you add methods it won't because they will conflict:

```php
trait T { function get() {} }
```

> Trait method get has not been applied, because there are collisions with other trait methods

The main question for this email: are there any valid use-cases which
do not conflict? Is there some way the methods *on the same class*
don't conflict? Using `T::get as get2` still conflicts because that
*aliases* even though most literature says it renames.

If not I would like to forbid it as part of an implementation of
generics I am working on.

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php
On 4 December 2017 17:26:12 GMT+00:00, Levi Morrison <[email protected]> wrote:
> Using `T::get as get2` still conflicts because that
>*aliases* even though most literature says it renames.

Funnily enough, I was just recently wondering why exactly that was, and couldn't find much of an answer. The RFC rather vaguely says that it would cause problems with dynamic dispatch, but it's not obvious to me why using "insteadof" to replace an inherited or locally declared method would be any different from using it to choose between two traits.

However, even if that limitation wasn't present, I can't see a use case for *directly* using the same trait twice in one class. I say directly, because even now you can *indirectly* introduce a trait twice, via inheritance of either the class or the trait.

trait A { function foo() {} }
trait B { use A; function bar() {} }
trait C { use A; function baz() {} }
class X {
use B, C { B::foo insteadof C; }
}
class Y extends X {
use A;
}

Regards,

--
Rowan Collins
[IMSoP]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php
Sorry, only registered users may post in this forum.

Click here to login