Web Analytics

PHP Abstract Classes

Intermediate~25 min read

Abstract classes are blueprints that can't be instantiated directly. They define methods that child classes MUST implement - perfect for enforcing structure!

Output
Click Run to execute your code

Abstract Class

<?php
abstract class Shape {
    abstract public function calculateArea();
    
    public function describe() {
        echo "I am a shape";
    }
}

// $shape = new Shape();  // Error! Can't instantiate
?>

Implementing Abstract Methods

<?php
class Circle extends Shape {
    private $radius;
    
    public function calculateArea() {
        return pi() * $this->radius * $this->radius;
    }
}
?>

Summary

  • abstract class: Cannot be instantiated
  • abstract method: Must be implemented by child
  • Use case: Enforce structure across subclasses

What's Next?

Next, learn about Interfaces - contracts that classes must follow!