Multi inheritance in PHP?
Written on 2023-03-20Join over 14k subscribers on my mailing list. I write about PHP news, share programming content from across the web, keep you up to date about what's happening on this blog, my work on Tempest, and more.
You can subscribe by sending an email to brendt@stitcher.io.
Ok so, this is an important topic. There's a new RFC: Interface Default Methods. Basically, it allows you to provide default implementations for interface methods, within the interface:
interface Clickable { public function handleClick( Point $point, Game $game ): void { $game->dispatch(new HandleClick($this)); } }
The reasoning of the RFC is that it allows for easier additions and changes to existing interfaces. A valid use case, but I'm most excited about how it allows a form of multi-inheritance.
Of course, we can already do a kind of multi-inheritance thanks to traits. The problem right now is that you cannot type hint for traits, and so you have to manually attach an interface to it. You might have seen this pattern before:
interface Clickable { public function handleClick( Point $point, Game $game ): void; } trait ClickableTrait { public function handleClick( Point $point, Game $game ): void { $game->dispatch(new HandleClick($this)); } } final readonly class Tile implements Clickable { use ClickableTrait; }
I like this interface default methods, because it gets rid of all this unnecessary boilerplate:
interface Clickable { public function handleClick( Point $point, Game $game ): void { $game->dispatch(new HandleClick($this)); } } final readonly class Tile implements Clickable { }
Of course, there are some side notes: interfaces don't support properties, so if you need to rely on internal state, you'll have to provide dedicated methods for it. That's a major drawback. Maybe, it would be better if we'd be able to type hint traits directly instead?
Food for thought.
In any case, I think this RFC is very interesting, and has lots of potential. However, several people find this proposal very strange: an interface shouldn't provide an implementation, right? Well, I've made a video about these concerns, and I would really like to read your comments on it as well!
Video: Multi Inheritance in PHP
Don't hesitate to hit reply to share your thoughts!
Until next time
Brent