You mix object composition and class inheritance.
Inheritance (implemented through the extends keyword) defines the relationship is a .
Composition defines the connection has a .
To illustrate this concept, we start with inheritance.
class Person { public $name; public function talk(){}; public function poop(){}; } class Parent extends Person { public function __construct($name) { $this->name = $name; } } class Child extends Person { public function __construct($name){ $this->name = $name; } }
In this example, we define a class things called people. From this definition, we get two different subtypes of "People, Parents, and Children." When we subtype a class, the subtype gets its own copy of all properties and has access to all methods defined in the base type, therefore, without its definition, the Child and the Parent have a name and can both speak and poop as well as be a person.
For instance:
$parent = new Parent("Homer"); $child = new Child("Bart"); $parent->talk(); $child->poop();
Composition is used when you want to realize a has a ship relationship. Let's review our definition of type Parent.
class Parent extends Person { public $children = array(); public function __construct($name) { $this->name = $name; } public function addChild(Child $child){ $this->children[] = $child; } }
What we now allow if for a parent to have a child.
$parent = new Parent("Homer"); $child = new Child("Bart"); $parent->addChild($child);
source share