amitmerchant1990 / amitmerchant-dot-com-comments

1 stars 0 forks source link

reasons-use-composition-over-inheritance-php/ #4

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

Reasons to use Composition over Inheritance in PHP – Amit Merchant – A blog on PHP, JavaScript and more

In object oriented programming, there are two ways using which classes can achieve polymorphic behaviour: “Inheritance” & “Composition”.

https://www.amitmerchant.com/reasons-use-composition-over-inheritance-php/

dominiquevienne commented 3 years ago

Thx, very useful to understand composition. Take a look at your multiple inheritance example: you do not set $this->tire in your Car constructor ;)

amitmerchant1990 commented 3 years ago

Great catch @dominiquevienne. I've fixed it now.

poppabear8883 commented 3 years ago

The issue is that you are trying to say that this will actually solve tight coupling, in which in itself does not.

The only true way to mitigate tight coupling is by coding to an interface. Yes when coding to an interface, and using the composition method it will remove the requirement of being tightly couple to a concrete implementation (the extended class).

There-for you can "extend" a classes functionality based on a contract and not a concrete class ..

But the article needs to show an actual example of loose coupling, the examples shown are still tightly coupled to a concrete class.

rintoug commented 1 year ago

Good writeup!

But check your first snippet, $this keyword missing in the accelerate function


class Car extends Vehicle
{

    public function accelarate()
    {    
        $this->move();    
    }
}
JLanky commented 1 year ago

It's a pity that you don't try on interfaces. Examples with interfaces in construction arguments were more descriptive

gurpreetkaits commented 3 months ago

nice, but can be more effective by using typed properties with interface ;) may be I'm talking about wider view. But still it's helpful.