Abstract Classes

Last updated on

PHP Abstract classes let you define shared traits while allowing each part to be unique. giving you an organized structure of code, and adaptable programming.

In this tutorial, you will understand what are abstract classes and how to use it. Let's get started.

Understanding PHP Abstract Classes

An abstract class is like a set of instructions you give to other classes. It is a setting up guidelines— So that any class “built” from this abstract class has to follow.

But here you can not create an object from an abstract class directly. Instead, you create other classes that extend this abstract class, and these classes fill in the details.

Let's take a look at a quick example:

abstract class Animal {
    // Abstract method (no body)
    abstract public function makeSound();

    // Regular method with full code
    public function breathe() {
        return "Breathing...";
    }
}

class Dog extends Animal {
    public function makeSound() {
        return "Bark!";
    }
}

// Create a Dog object
$dog = new Dog();
echo $dog->makeSound(); // Output: Bark!
echo $dog->breathe(); // Output: Breathing...

Look at the above example and check the following list:

  • Animal is an abstract class, meaning it’s like a model or template.
  • It has an abstract method makeSound(), which has no body; this must be implemented by any child class.
  • There’s also a regular method breathe() that is fully defined, meaning any child class (like Dog) will inherit this functionality.

So the question is, Why Use Abstract Classes?

If you’re creating a bunch of similar objects in a project—different kinds of users on a site or various types of animals in a simulation—they will have shared actions.

But each type might also need to behave differently in certain situations. Abstract classes let you define those common actions just once, saving you time and reducing duplicate code.

For instance, you might have an abstract class called User with a shared login() method, but leave the specifics of other actions (like postContent() for a social media site) up to the individual classes (like Admin, Subscriber, etc.).

Anyway, in the following section, you will see an example.

Example of Using Abstract Classes

Consider that you are building an online store with multiple payment options—credit cards, PayPal, and so on. Each payment method needs similar steps: validate details, process payment, and confirm the transaction.

Here are the benefits of abstract class—it lets you set up the shared steps in one place and customize each payment type as needed.

Let's see that in example:

abstract class PaymentProcessor {
    abstract protected function validatePaymentDetails();

    public function processPayment() {
        // Common steps for any payment method
        $this->validatePaymentDetails();
        $this->deductAmount();
        $this->confirmTransaction();
    }

    protected function deductAmount() {
        echo "Amount deducted.\n";
    }

    abstract protected function confirmTransaction();
}

class CreditCardPayment extends PaymentProcessor {
    protected function validatePaymentDetails() {
        echo "Validating credit card details.\n";
    }

    protected function confirmTransaction() {
        echo "Transaction confirmed via credit card.\n";
    }
}

$payment = new CreditCardPayment();
$payment->processPayment();

This structure makes adding a new payment option a breeze. Just extend PaymentProcessor, fill in the blanks for the unique steps. So, no need to rewrite the basics!

Here you will find the differences between abstract classes and Interfaces. Anyway, in the following section

Wrapping Up

PHP abstract classes give your code a foundation but leave room for customization. With an abstract class, you set the expectations (methods to be implemented) without dictating every little detail.

Here is a quick recap:

  • Abstract classes are templates with some shared code and some requirements.
  • They help you write DRY (Don’t Repeat Yourself) code and make it easy to add new elements to a project.

Thank you for reading. Happy Coding!

Frequently Asked Questions (FAQs)

  • What is a 'PHP abstract class'?

    A PHP abstract class is a template for other classes, defining shared methods and requiring specific methods without giving all the details.
  • How do you define an abstract class in PHP?

    To create an abstract class, use the abstract keyword before the class name. Example:
    abstract class Animal {
        abstract public function makeSound();
        public function breathe() {
            return "Breathing...";
        }
    }
  • Can I create an instance of an abstract class in PHP?

    No, you cannot create an instance of an abstract class. Instead, you create child classes that extend the abstract class and implement its abstract methods.
  • What’s the purpose of an abstract method in PHP?

    An abstract method is declared without a body, meaning it must be defined in any subclass. It sets expectations for child classes without enforcing how they work.
  • How do I use an abstract class with child classes?

    You extend the abstract class and define any required abstract methods in the child class. Example:
    class Dog extends Animal {
        public function makeSound() {
            return "Bark!";
        }
    }
  • Why use abstract classes in PHP?

    Abstract classes allow you to define common functionality once while leaving specifics to child classes. This makes code more organized and reduces duplication.
  • How is an abstract class different from an interface?

    An abstract class can include shared code (like regular methods), while an interface only defines method requirements. Use an abstract class for shared behavior with specific details left for subclasses.
  • What’s an example of an abstract class in a payment system?

    An abstract class can define shared payment steps with customizable actions for each payment method. Example:
    abstract class PaymentProcessor {
        abstract protected function validatePaymentDetails();
    
        public function processPayment() {
            $this->validatePaymentDetails();
            $this->deductAmount();
            $this->confirmTransaction();
        }
    
        protected function deductAmount() {
            echo "Amount deducted.\n";
        }
    
        abstract protected function confirmTransaction();
    }
    
    class CreditCardPayment extends PaymentProcessor {
        protected function validatePaymentDetails() {
            echo "Validating credit card details.\n";
        }
    
        protected function confirmTransaction() {
            echo "Transaction confirmed via credit card.\n";
        }
    }
    
    $payment = new CreditCardPayment();
    $payment->processPayment();
  • How do abstract classes help with DRY (Don’t Repeat Yourself) principles?

    Abstract classes allow you to write shared methods once, which child classes can inherit. This avoids repeating the same code in multiple places, keeping the codebase cleaner.
  • Can an abstract class have regular methods in PHP?

    Yes, an abstract class can have both abstract (no body) and regular methods (with full code), allowing shared functionality and customization points.
Share on: