Re: Class Extension
| From: | Holly Schilling | Date: | Fri, 10 Jul 2026 05:02:13 +0000 |
| Subject: | Re: Class Extension | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-131850@lists.php.net to get a copy of this message | ||
First, my apologies to the readers. Something is chewing up my formatting and indenting. I’m still
trying to figure out a cause.
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?
If we ignore precise syntax and implementation, this is exactly the mental model of my RFCs and
implementations. It is applying a trait to an existing class that you don’t control.
The similarities don’t end there. This is the same infrastructure as what is used to implement
this feature.
The reason I don’t feel the
trait … for syntax is appropriate is because of
$this. In a function inside a typical trait, $this refers to an instance
of the trait. In an extension, $this refers to an instance of the class being extended.
Adding the for block to the trait changes the type of $this in the entire
trait. That is unintuitive and likely to introduce barriers to understanding.
Holly