PHP Abstract Classes

PHP Abstract Classes

Abstract classes and methods are used when the parent class has a named method, but requires its child classes to actually write out the tasks.

An abstract class is a class that contains at least one abstract method. An abstract method is a method that is declared, but not implemented in the code (it has no body).


The abstract Keyword

An abstract class or method is defined with the abstract keyword.

Important Rules:

  1. You cannot create an object directly from an abstract class (new ParentClass will fail). It only exists to be inherited.
  2. When a child class inherits from an abstract class, it must implement all of the parent's abstract methods.

Abstract Class Example

<?php
// Parent class
abstract class Car {
  public $name;
  public function __construct($name) {
    $this->name = $name;
  }
  

// Abstract method: Note that it has no body {} abstract public function intro() : string; }

// Child class class Audi extends Car { // The child MUST provide the body for the abstract method public function intro() : string { return "Choose German quality! I'm an $this->name!"; } }

$audi = new Audi("Audi"); echo $audi->intro(); ?>

Abstract classes are excellent for forcing a strict blueprint across a team of developers, ensuring certain methods are never forgotten.