I like how extensions in Swift allow to organise code!

If we ignore implementation details and ownership it's pretty similar to what 
we have with traits. In PHP, what would be the benefit of extensions over 
traits? One thing that comes to my mind is that traits can be used by whatever 
chooses to add it (back to ownership). Good one, but what else? If ownership is 
the only concern then maybe a small addition to traits could achieve the same?


```
trait Foo
{
    for Baz\Bar::class;  // inverse of "use" to limit usage
}

class Bar
{
    use Foo;
}
```

Brings conflict resolution for free; and I think it would be cheaper than yet 
another class-like thing. Maybe also feels more php-ish since we already have 
the trait concept?


Thanks for the feedback, Nick.

An extension is essentially the reverse of a trait. With a trait, the trait use 
is declared within the class definition and all users of the class get those 
methods. With an extension, they are generally NOT declared by the one who 
defines the class. They are instead declared by the user of the class. They are 
purely syntactic sugar, but they are very nice to have. You can see my example 
with \DateTimeImmutable I sent earlier for an example.

It’s a feature for what I’ve called Phase 2, but scoping the extensions is 
where they become powerful. An extension can provide functionality similar to a 
default implementation on Interface, although the method cannot be a required 
member on the interface.

Holly

Reply via email to