What are the advantages and disadvantages of using composition over inheritance when defining types in PHP?
When defining types in PHP, using composition over inheritance can offer more flexibility, reusability, and maintainability in your code. Composition allows you to build complex objects by combining simpler ones, which can lead to a more modular and easier-to-understand codebase. However, it can also introduce more complexity and require additional boilerplate code compared to inheritance.
<?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();
?>