SyntaxStudy
Sign Up
PHP Intermediate 8 min read

Abstract Classes

An abstract class is a class that cannot be instantiated directly — it exists solely to be extended. Abstract methods declare a method signature without providing an implementation, forcing subclasses to provide one.

  • Declare with abstract class ClassName.
  • Abstract methods: abstract public function name(): returnType; — no body.
  • Abstract classes can contain concrete (implemented) methods and properties.
Example
<?php
abstract class Shape
{
    public function __construct(protected string $color = 'black') {}

    // Subclasses MUST implement these
    abstract public function area(): float;
    abstract public function perimeter(): float;

    // Concrete method — shared by all shapes
    public function describe(): string
    {
        return sprintf(
            '%s %s — Area: %.2f, Perimeter: %.2f',
            ucfirst($this->color),
            static::class,      // late static binding
            $this->area(),
            $this->perimeter()
        );
    }
}

class Circle extends Shape
{
    public function __construct(private float $radius, string $color = 'red')
    {
        parent::__construct($color);
    }

    public function area(): float
    {
        return M_PI * $this->radius ** 2;
    }

    public function perimeter(): float
    {
        return 2 * M_PI * $this->radius;
    }
}

class Rectangle extends Shape
{
    public function __construct(
        private float $width,
        private float $height,
        string $color = 'blue'
    ) {
        parent::__construct($color);
    }

    public function area(): float      { return $this->width * $this->height; }
    public function perimeter(): float { return 2 * ($this->width + $this->height); }
}

$shapes = [new Circle(5), new Rectangle(4, 6)];
foreach ($shapes as $shape) {
    echo $shape->describe() . "
";
}

// new Shape(); // Fatal Error: Cannot instantiate abstract class
Pro Tip

Tip: Use an abstract class when you want to share concrete code (methods, properties) alongside an enforced contract. If you need only the contract without shared implementation, use an interface instead.