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).
abstract KeywordAn abstract class or method is defined with the abstract keyword.
Important Rules:
new ParentClass will fail). It only exists to be inherited.
<?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.