OOP: Composition & Inheritance in PHP

Adrienne Domingus
4 min readJun 7, 2021

Inheritance is one of the primary tenets of object-oriented programming languages, but each language implements it at least slightly differently. 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. Here is what I have learned!

Extends

The extends keyword in PHP is inheritance as I knew it — one class inherits behavior from another, but can extend and modify it. The PHP docs are here. Classes at all levels of this hierarchy can be instantiated.

In addition to adding new behavior, subclasses can modify existing behavior by calling its parent. Let’s take a look at an example.

class Clothing {    private $size;
private $description;
public function __construct(int $size, string $description) {
$this->size = $size;
$this->description = $description;
}
public function getSize() : int {
return $this->size;
}
public function getDescription() : string {
return $this->description;
}
}class Pants extends Clothing { public function getDescription() : string {
return 'A pair

--

--