2

What do you guys think of php's traits?

For those that don't know, traits provide copy/paste discount inheritance functionality. You can include common methods or properties. For example, I use the TimestampableEntity trait to include createdAt, id and updatedAt fields to my entities. They're really useful for simple stuff. You can include multiple traits in one class and it will error on clashing methods/properties

Comments
  • 2
    Love them for just that, also that you're able to overload them and/or choose which to import if there are compeeting.

    The only thing that's lacking for me are kind of "generics" with them. Let's assume we habe a traitA, traitB and traitC they basically are copy passt but with different properties. Sure we can combine them by using them Insider another traut and just using that one in the actually class, but still we have to write the code multiple times... Sure we could just have a trait, that has a function accepting also a propertyname like `setFoo($prop, $val=null): void { $this->$prop = $val; }` (and do some whitelisting what so ever) but that then just feels Like the magic __get/__set functions...

    So, I love them, but I do feel that there is room for improvement how they are implemented by the language itself. But before fuxing that, I'd love to get arrays with a type something like `Class[]` which we're using for documentation allready, for the returntypes.
  • 1
    @Wack I totally agree with the typed lists, docblocks are useful for typehinting arrays but an actual typehint is something that I miss having used java/c#
  • 1
    Have you heard about https://github.com/msgphp/... before? It uses traits all over the place to keep users as generics as possible (ex. unlike FOS doesn't require a username and E-Mail, etc.)

    It's an impressive display of what traits can do if you let them.
Add Comment