Abstract in OOP PHP

In this tutorial we will discuss about abstract in OOP PHP. Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method’s signature.

When inheriting from an abstract class, all methods marked abstract in the parent’s class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility.
For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.

Abstract classes in php are similar like other oop languages. You can create abstract classes in php using abstract keyword. Once you will make any class abstract in php you can not create object of that class.Abstract classes in php are only for inheriting in other class.
Example below will throw fatal error

 abstract class abc
{
	public function xyz()
{
	return 1;
}
}
$a = new abc();//this will throw error in php

The Example below will not throw any Error:

 abstract class testParent
	{
	public function abc()
	{
		//body of your funciton
	}
	}
	class testChild extends testParent
	{
	public function xyz()
	{
		//body of your function
	}
	}
	$a = new testChild();

In above example you are creating of testChild Class. TestChild class is inheriting testParent abstract class. So your abstract class is only available for inheritance. Main motive of creating abstract classes in php is to apply restriction of direct initialization or object creation.

As we know that abstract functions are those functions of abstract class which is only defined. It will be declared in your child class. You can create any method abstract using keyword abstract. You can only create abstract method either in abstract class or interface.

Important

If you have an abstract method in your abstract class then once you inherit your abstract class then it is necessary to declare your abstract method. If you will not declare your abstract method then PHP will throw error in that case.You can declare your abstract method in child class with the same visibility or less restricted visibility.

For more Read OOP in PHP