OOP: Composition & Inheritance in PHP
--
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 of pants: ' . parent::getDescription();
}}
This is a basic example where we have one layer of inheritance — Pants
are a piece of Clothing
. From this example, we can see that an instance of the Pants
class can use getSize
from Clothing
, and apply modifications to getDescription
by using parent
.
php > $p = new Pants(10, 'blue and cozy');
php > var_dump($p->getDescription());
string(30) "A pair of pants: blue and cozy"
php > var_dump($p->getSize());
int(10)
Interfaces
The idea of interfaces were new to me — you can read the documentation here. Interfaces define the methods and properties that a class needs to implement, but doesn’t actually implement them. This includes their access levels (public
or private
or protected
) and the types of the inputs and outputs. Names of the functions must match, in addition to signatures and types. Interfaces…