What are common pitfalls to avoid when using extends keyword in PHP classes for inheritance?
One common pitfall to avoid when using the `extends` keyword in PHP classes for inheritance is creating a deep inheritance hierarchy, which can lead to complex and hard-to-maintain code. To solve this, it's recommended to favor composition over inheritance when possible, and only use inheritance when there is a clear "is-a" relationship between the classes.
// Example of using composition over inheritance
class Engine {
public function start() {
echo "Engine started";
}
}
class Car {
private $engine;
public function __construct() {
$this->engine = new Engine();
}
public function start() {
$this->engine->start();
echo "Car started";
}
}
$car = new Car();
$car->start();