How to Use Abstract Class in PHP

Introduction

I will describe abstract classes in PHP. An abstract class is defined using the abstract keyword and abstract is a type of class. An object can't be created as an abstract class using the new keyword. Also, an abstract class can't directly create an object by the class. And an abstract class is something like an interface in PHP. Basically an abstract class implements a class using abstract. We can't extend using more than one abstract class when we implement more than one interface.

Simple Abstract Class

<?php

  abstract class technology()

  {

 

  }

  $new_technology = new technology();

?>

This will show an error such as "can't instantiate the abstract class".

How to Define an Abstract Method

An abstract method is defined using the abstract keyword, as in:

<?php

  abstract class technology()

  {

  abstract function set_name()

    {

 

    }

  }

?>

Static Method Defined in the Proper way

<?php

  abstract class technology()

  {

  abstract function set_name()

  }

?>

The class that contains the abstract method must be defined as abstract.

Extending the abstract class

Extending the abstract class to be used as the method of a class. To call an abstract method you must extend the class in the class. Your implementation code can be written in the child class. The child class can be implemented in all abstract methods of the parent class and the access level of the method such as the child class to the parent class the same or lower.

An abstract method can be defined as public in the abstract class but you cannot implement it as private or protected in the child class.

Example

 

<?php

abstract class technology

{

  abstract function set_name();

}

 

class Profile extends technology

{

  function set_name()

  {

    echo "PHP";

  }

}

 

 

$obj_profile = new profile();

 

$obj_profile->set_name();

?>

In the child class you must implement all abstract methods of the parent class.

Output

Abstract class in PHP.jpg

Abstract classes work something like an interface in PHP. 


Similar Articles