PHP Keywords: abstract

22 February 2019 - 9:55pm

Welcome to my series on every PHP keyword and its usage. Today's item: abstract.

The 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 abstract class.

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.

Note:

  • An abstract class can extend a concrete class.
  • A property cannot be marked abstract.
  • Both normal and static methods can be marked abstract.

Usage

<?php
abstract class Asset
{
    private $path = "";
    private $minifiedPath = null;

    public function __construct($path)
    {
        $this->path = $path;
    }

    public function getPath()
    {
        return $this->path;
    }

    // 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);
        }

        return $this->minifiedPath;
    }
}

class Script extends Asset
{
    // Extended methods must have the same name, argument types and return
    // type. Arguments can have different names, though.
    protected function minify(string $javascriptPath): string
    {
        return JavascriptMinifier::minify($javascriptPath);
    }
}

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

Traits can also have abstract methods. An abstract method within a trait must be implemented by the class that uses that trait.

<?php
trait NameComparable
{   
    public static function compareNames(self $first, self $second): int
    {
        return $first->getName() <=> $second->getName();
    }

    public abstract function getName(): string;
}