Skip to content

abstract

Understanding the abstract Keyword in PHP

In PHP, the abstract keyword is used to define abstract classes and abstract methods. An abstract class is a class that cannot be instantiated and is meant to be subclassed by other classes. An abstract method is a method that is declared in an abstract class but does not provide an implementation.

What is an Abstract Class?

An abstract class is a class that cannot be instantiated. It is meant to be subclassed by other classes, which can provide concrete implementations of its abstract methods. An abstract class can have both abstract and non-abstract methods. However, if a class contains at least one abstract method, it must be declared as abstract.

What is an Abstract Method?

An abstract method is a method that is declared in an abstract class but does not provide an implementation. Instead, the implementation is provided by a subclass of the abstract class. An abstract method is declared using the abstract keyword and does not include a method body.

How to Define an Abstract Class and Method in PHP

To define an abstract class in PHP, use the abstract keyword before the class keyword. An abstract method is declared inside the class using the abstract keyword, followed by the visibility modifier, method name, and parameters, but without a method body.

php
<?php

abstract class Animal {
   abstract public function makeSound();
}

Any class that extends the abstract class must implement all its abstract methods. Here is a practical example:

php
<?php

class Dog extends Animal {
   public function makeSound() {
      echo "Woof!";
   }
}

$dog = new Dog();
$dog->makeSound(); // Output: Woof!

Note: Abstract methods cannot be declared as private or static in PHP. They must be public or protected.

Conclusion

The abstract keyword in PHP is used to define abstract classes and methods. An abstract class cannot be instantiated and is meant to be subclassed by other classes. An abstract method is a method that is declared in an abstract class but does not provide an implementation. Instead, the implementation is provided by a subclass of the abstract class. Understanding how to use the abstract keyword in PHP can help you write more effective and efficient code.

Practice

What are the rules regarding abstract classes and methods in PHP as explained on w3docs.com?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.