What are the advantages of using aggregation over inheritance for passing objects between classes in PHP?
Using aggregation over inheritance for passing objects between classes in PHP allows for more flexibility and modularity in the code. Aggregation allows classes to be loosely coupled, making it easier to change or swap out objects without affecting the overall structure of the code. This approach also promotes better code reusability and maintainability.
<?php
class Engine {
public function start() {
echo "Engine started\n";
}
}
class Car {
private $engine;
public function __construct(Engine $engine) {
$this->engine = $engine;
}
public function start() {
$this->engine->start();
echo "Car started\n";
}
}
$engine = new Engine();
$car = new Car($engine);
$car->start();