PHP - Abstract Classes

Abstract classes are a fundamental concept in object-oriented programming (OOP) that serve as blueprint or templates for other classes. They cannot be instantiated on their own; they are meant to be subclassed. Abstract classes allow you to define common properties and methods that subclasses should implement, while providing a structure for code reuse and maintaining a consistent design. In PHP, you can create abstract classes using the abstract keyword. Here's how abstract classes work in advanced PHP:

Defining an Abstract Class:

abstract class Animal {
  protected $name;
  public function __construct($name) {
      $this->name = $name;
  }
  abstract public function makeSound();
  public function getName() {
      return $this->name;
  }
}

In the example above:

The Animal class is defined as an abstract class using the abstract keyword.

The abstract class includes a constructor that initializes the common property $name.

The makeSound() method is declared as abstract using the abstract keyword. Subclasses must provide an implementation for this method.

The getName() method is implemented in the abstract class and can be used by all subclasses.

Creating Subclasses:

class Dog extends Animal {
  public function makeSound() {
      return "Woof!";
  }
}
class Cat extends Animal {
  public function makeSound() {
      return "Meow!";
  }
}

In this example, both the Dog and Cat classes extend the abstract class Animal and provide concrete implementations for the abstract makeSound() method.

Using Abstract Classes:

$dog = new Dog("Buddy");
$cat = new Cat("Whiskers");
echo $dog->getName() . " says " . $dog->makeSound();  // Output: Buddy says Woof!
echo $cat->getName() . " says " . $cat->makeSound();  // Output: Whiskers says Meow!

Key points about abstract classes in PHP:

Abstract classes cannot be instantiated directly; they serve as blueprints for subclasses.

Abstract classes can have properties, methods (both abstract and concrete), and constructors.

Abstract methods are declared using the abstract keyword and must be implemented by subclasses.

Subclasses that extend an abstract class must provide implementations for all abstract methods.

Non-abstract methods in abstract classes can provide common functionality shared by subclasses.

Abstract classes can also have concrete methods that provide default behavior.

Abstract classes allow you to define a common interface for a group of related classes.

Abstract classes are valuable when you want to define a common structure and behavior for a group of classes that share a certain relationship or hierarchy. They help ensure that subclasses adhere to a common contract and provide a consistent design pattern.