PHP Abstract Classes
Abstract classes in PHP are classes that cannot be instantiated on their own and are meant to be extended by other classes. They can contain abstract methods (which must be implemented by subclasses) as well as concrete methods (which can have their functionality).
Defining an Abstract Class
<?php
abstract class Animal {
abstract public function makeSound();
public function sleep() {
return "Sleeping...";
}
}
?>
Explanation: This example defines an abstract class Animal
with an abstract method makeSound
and a concrete method sleep
.
Extending an Abstract Class
<?php
class Dog extends Animal {
public function makeSound() {
return "Bark";
}
}
class Cat extends Animal {
public function makeSound() {
return "Meow";
}
}
?>
Explanation: This code demonstrates how to extend the Animal
abstract class with two concrete classes, Dog
and Cat
, which implement the makeSound
method.
Instantiating Subclasses
<?php
$dog = new Dog();
echo $dog->makeSound(); // Outputs: Bark
$cat = new Cat();
echo $cat->makeSound(); // Outputs: Meow
?>
Explanation: This example shows how to create instances of the Dog
and Cat
classes and call their respective makeSound
methods.