Composition¶
Composition is the creation of new classes, by including other classes, and delivering a specific interface over them.
<?php
class Wheel {
int $diameter;
}
class GasTank {
int $capacity;
public function fillUp(int $amount) {
$this->amount = $amount;
}
public function empty() {
$this->amount = 0;
}
}
// Car composes 2 other classes: GasTank and Wheel
// These object should be accessed via the Car class, not the direct objects
class Car {
Wheel $wheels;
GasTank $gasTank;
public function fillUp(int $amount) {
$this->gasTank->fillUp($amount);
}
// empty() the gasTank is now available via the car (just drive it, or and it to garage)
}
?>
See also Composition Over Inheritance in PHP, Object composition in PHP with Example
Related : Inheritance