How can PHP classes be structured to improve code flexibility and maintainability?
PHP classes can be structured using principles such as encapsulation, inheritance, and polymorphism to improve code flexibility and maintainability. Encapsulation helps in hiding the internal state of an object and only exposing necessary functionality through methods. Inheritance allows for creating a hierarchy of classes where child classes inherit properties and methods from parent classes. Polymorphism enables objects of different classes to be treated as objects of a common superclass.
class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class Dog extends Animal {
public function bark() {
return "Woof!";
}
}
class Cat extends Animal {
public function meow() {
return "Meow!";
}
}
$dog = new Dog("Buddy");
echo $dog->getName(); // Output: Buddy
echo $dog->bark(); // Output: Woof!
$cat = new Cat("Whiskers");
echo $cat->getName(); // Output: Whiskers
echo $cat->meow(); // Output: Meow!