Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

James Lewis:
Composition over Inheritance PHP Style
Dec 28, 2015 @ 16:49:45

In this post to his site James Lewis makes the suggestion that you consider composition over inheritance when it comes to writing your object-oriented PHP. That is, using PHP's traits functionality to compose interfaces with only the functionality needed, not other possibly useless things.

So what does “composition over inheritance” mean? [...] Lets dive into an example written in PHP to help us better understand composition over inheritance. [...] Almost all modern programming languages have a way of dealing with composition, PHP has Traits. Traits where introduced into PHP at version 5.4 and the PHP docs describes traits as a mechanism for code reuse.

He starts with an example of using inheritance to create new "animal" types but points out that this can lead to extra functionality as sometimes your Robocat just doesn't need to eat. He then introduces traits as a way around the issue, creating traits for each piece of functionality and using PHP's use statement to include only the ones needed for that particular kind of object.

tagged: composition style inheritance traits opinion

Link: http://blog.jwlewisiii.com/composition-over-inheritance-php-style/


Trending Topics: