PHP Abstract Classes

Introduction to PHP Abstract Classes

The abstract classes and methods have been introduced in PHP5. Abstract classes and methods are used to implement an abstract oriented programming abstraction feature.

The abstraction is a process in which the programmer hides the unnecessary data and only shows the data that is in the context of the end user. This reduces the complexity of the program and increases the ease of use.

Let’s now try to know about abstract methods and classes.

Abstract Methods

Abstract methods They are methods.

  1. Those who do not have a method body.
  2. Whose names and parameters are declared.
  3. Which are declared with abstract keyword.

Abstract methods are only defined in abstract classes. Their body provides the class which inherits the abstract class.

Abstract Classes

Abstract class is class in which there is one or more abstract methods and is defined by abstract keyword. Some important charcterstics are given below of the abstract classes, which makes them different from the other classes.

The object of an abstract class can not be created. These are classes that are made to inherit only. The main reason for creating abstract classes is to create a template that can force the inheriting class to implement abstract methods.

  1. If there is one or more abstract method in a class then it is mandatory that the class is also abstract.
  2. Normal properties and methods can be declared in addition to abstract methods in an abstract class.
  3. It is mandatory to define the body of all the abstract methods defined in the class abstract class that inherits the abstract class.
  4. Abstract class can declare class abstract classes and abstract methods with the same visibility or with less secure visibility.
  5. Abstracts class which inherits class and signature methods of abstract class must match perfectly.

One thing you should always keep in mind is that abstract class does not support multiple inheritance. Although an abstract class can inherit another abstract class, but the normal class inheriting the abstract class should not be inherited by a second class.

The simple example of implementing abstract classes in the following PHP is being given.

<?php
abstractClasses.php
// here, class should be declared as abstract
abstract class Hello {
public abstract function sayHello();
}
class Hey extends Hello {
public function sayHello(){
return "Hello";
}
}
$greeting = new Hey;
echo $greeting->sayHello();
?>