Is extending classes in PHP a better solution to avoid duplicate object instances and improve code organization?
Extending classes in PHP can be a better solution to avoid duplicate object instances and improve code organization. By creating a base class with shared properties and methods, you can then create subclasses that inherit these attributes. This allows you to reuse code and prevent the need for redundant object instantiation.
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function speak() {
echo "Animal sound";
}
}
class Dog extends Animal {
public function speak() {
echo "Woof!";
}
}
class Cat extends Animal {
public function speak() {
echo "Meow!";
}
}
$dog = new Dog("Buddy");
$cat = new Cat("Whiskers");
$dog->speak(); // Output: Woof!
$cat->speak(); // Output: Meow!