Home » Development » Clean up your toolbox with PHP traits …
Single inheritance has often been the limitation for PHP. This means that a class can only inherit from one other class. Often classes share the same methods and it would be beneficial to allow reuse and prevent duplication.
In PHP 5.4 a new feature was added, known as Traits. A Trait is like a Mixin, allowing to use / mix classes into existing classes. This means code reduction and less duplication.
Example of a Trait
This trait can than be used in other classes:
Both classes can now use the Shareable trait.
The benefit is less code duplication. The drawback is, that not all used methods are visible within the source-code of the class. So before moving a method to a trait, make sure that you will actually reuse it ;)
I have been restructuring huge amounts of code over the past months and traits are helping to keep things far more organized.
In combination with __autoload its a real nice way to cleanup your code toolbox.
Happy coding Alex
Alexander Gräf
Portfolio
Book Me
Get in touch
Live Chat
Ich bin ein Full-Stack-Entwickler. Meine Expertise umfasst:
Ich liebe die Entwicklung, das Design und kenne mich auch mit Serverarchitekturen aus. Ich würde mich nie vollständig fühlen, wenn einer der Bereiche fehlen würde.
Ich habe ein breites Interessengebiet, deshalb tauche ich ständig in neue Technologien ein und erweitere mein Wissen, wo immer es nötig ist. Die Technologien entwickeln sich schnell und ich genieße es, die neuesten Technologien zu nutzen.
Abgesehen davon bin ich ein friedliebender Kerl, der versucht, Leute um sich herum zu haben, die dasselbe denken. Ich glaube wirklich an das Prinzip: "Wenn man jemandem hilft, wird einem jemand helfen, wenn man es braucht."