An abstract class in PHP is a class that cannot be instantiated on its own and is meant to be inherited by other classes. It can contain abstract methods, which are methods declared without a body that must be implemented by subclasses, as well as regular methods that may have implementations. This structure allows for defining a common interface and shared functionalities across different subclasses.
Abstract classes are useful in scenarios where you want to provide a common base for other classes that share certain common traits but also require specific implementations.
Here's an example of using an abstract class in PHP:
<?php
abstract class Animal {
// Abstract method
abstract protected function makeSound();
// Regular method
public function sleep() {
return "Sleeping...";
}
}
class Dog extends Animal {
public function makeSound() {
return "Bark";
}
}
class Cat extends Animal {
public function makeSound() {
return "Meow";
}
}
$dog = new Dog();
echo $dog->makeSound(); // Outputs: Bark
echo $dog->sleep(); // Outputs: Sleeping...
$cat = new Cat();
echo $cat->makeSound(); // Outputs: Meow
echo $cat->sleep(); // Outputs: Sleeping...
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?