Sobes.tech
Junior — Middle

What methods of implementing and using abstract classes are you familiar with?

sobes.tech AI

Answer from AI

Abstract classes in PHP are used to define a base template that cannot be instantiated directly but can contain both abstract methods (without implementation) and methods with implementation.

Usage methods:

  • Declaring an abstract class with the keyword abstract.
  • Defining abstract methods that must be implemented in child classes.
  • Using an abstract class as a base for inheritance to ensure a common interface and behavior.

Example:

abstract class Animal {
    abstract public function makeSound();

    public function sleep() {
        echo "Sleeping...";
    }
}

class Dog extends Animal {
    public function makeSound() {
        echo "Bark!";
    }
}

$dog = new Dog();
$dog->makeSound(); // Outputs: Bark!
$dog->sleep();     // Outputs: Sleeping...

Thus, abstract classes allow creating a framework for future classes and ensuring the mandatory implementation of certain methods.