When should composition be preferred over inheritance in PHP class design?
Composition should be preferred over inheritance in PHP class design when there is a "has-a" relationship between classes rather than an "is-a" relationship. This means that one class contains an instance of another class as a member, rather than inheriting behavior from a parent class. This approach promotes better code reusability, flexibility, and maintainability.
class Engine {
public function start() {
echo "Engine started";
}
}
class Car {
private $engine;
public function __construct() {
$this->engine = new Engine();
}
public function startCar() {
$this->engine->start();
echo "Car started";
}
}
$car = new Car();
$car->startCar();
Related Questions
- What are the advantages and disadvantages of using system calls or shell commands to interact between Java and PHP?
- Is it possible to control hardware devices like microphones through a website using PHP, considering its server-side limitations?
- Is there a more efficient way to write data to the beginning of a .csv file in PHP?