PHP abstract Classes and Methods – How to create in PHP

PHP Abstract Classes and Methods: Sometimes when creating a program we needed to create a class but restrict it to somewhat where its object should not be created.

In those cases, we create PHP abstract classes and methods.

An abstract class is a class where we only named a class or method in the main class but its needs a child class to fill out the task.

What are PHP Abstract Classes and Methods?

Abstract classes and methods are just named methods but we didn’t define the task of what is there but in its child class.

Suggested: PHP Inheritance: Concept, Override method, Modify & Final keyword

Both abstract class and function are defined using abstract keywords.

Abstract classes and methods are useful when we know we have to create methods but we are not yet sure what to do with them.

We can’t create an object from an abstract class but we can create a derived class of it that uses the same name and there we define what that class or function would do.

The child class or method should have an equal or less restricted modifier.

How to Create Abstract Classes or Methods?

For example, if we are going to create an abstract class or method here is how we can do it:


//Defining abstract class
abstract class MyParentClass{
    abstract public function myAbstractFunction();
}

Here as you can see:

  • We defined a class with the keyword ‘abstract’, this is basically how we create an abstract class.
  • We also define an abstract function which is defined in the same way as we create an abstract class.

So now if we want to create a class that inherits that abstract class, here is how to do

Here is a simple example of the abstract class in PHP:


// Inherit Abstract class
class MyChildClass extends MyParentClass{
    // Inherit Abstract method
    public function myAbstractFunction(){
        echo 'This is name';
    }
    
}

So in simple terms, we create an abstract class where we don’t want to create its objects but want to, later on, expand it creating its child class.

So in essence:

  • We can’t create objects of abstract classes directly.
  • If there is an abstract method inside a class, that class must be abstract too. However abstract classes are not required to have abstract methods.
  • The abstract method of the class must be defined inside the subclass.