Source: adriennedomingus.medium.com

OOP: Composition & Inheritance in PHP

Category: PHP

We think you might be interested in this job:

I’m coming from a background in Python, and it took me a bit to understand the different ways objects can extend or inherit behavior in PHP.

The extends keyword in PHP is inheritance as I knew it — one class inherits behavior from another, but can extend and modify it.

Traits allow you to define methods and implement their behavior and reuse those pieces of logic in other classes without any hierarchy or assumed relationship between different objects that use a given trait, and importantly, with the ability to use as many as you like.

For example, if we tried to define another trait with the getWashingInstructions method, and tried to apply it to our Couch class as well, we’d see an error that looks like this: You can however, redefine the method on the class itself, and override the behavior entirely.

Namespaces can help you organize your code, and are an important concept in Object Oriented programming, but are beyond the basics of inheritance in PHP, so not covered here!
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Community Partners