Welcome to my series on every PHP keyword and its usage. Today’s item:
abstract keyword can be used to enforce that a class or method cannot be used directly, but must be extended. An
abstract method can only be used inside of an
When a class is marked
abstract, it must be extended. When a method is marked
abstract, it must be overridden with the same signature. In this way, it is similar to an interface.
The primary difference between an abstract class and an interface, is that an abstract class can have concrete methods and properties, as well as abstract methods.
If you can choose between an interface and an abstract class, always choose an interface. Any class can implement an interface, while only a class with no parent can extend an abstract method.
- An abstract class can extend a concrete class.
- A property cannot be marked
- Both normal and
static methods can be marked
abstract class Asset
private $path = "";
private $minifiedPath = null;
public function __construct($path)
$this->path = $path;
public function getPath()
// Abstract methods have no body, and have a semicolon at the end
protected abstract function minify(string $path): string;
public function getMinifiedPath()
if($this->minifiedPath === null)
$this->minifiedPath = $this->minify($this->path);
class Script extends Asset
// Extended methods must have the same name, argument types and return
// type. Arguments can have different names, though.
class Styles extends Asset
// You can add more arguments when extending an abstract method, but they
// must have default values
protected function minify(string $path, bool $simplify = true): string
return CssMinifier::minify($path, $simplify);
Traits can also have abstract methods. An abstract method within a trait must be implemented by the class that uses that trait.
public static function compareNames(self $first, self $second): int
return $first->getName() <=> $second->getName();
public abstract function getName(): string;