In PHP, Abstract class cannot be instantiated (means object cannot be created), to use abstract class, other class must extend it and implement all its abstract methods. Abstract class can have both abstract or non abstract (concrete) methods. Abstract methods only provide method signature without function body {} and its code.
Because object of Abstract classes cannot be created. Abstract classes act as template for other classes to extend.
- Abstract class must have at least one abstract method.
- Constructor can also be created inside abstract class in PHP
- A class can only extend one abstract class.
- It provides common Abstract methods for other classes to implement.
Syntax
An Abstract class declaration is similar to other classes except abstract keyword is used before class keyword.
abstract class classname{
// abstract method
abstract function function_name();
abstract function function_name(arguments);
// Non-abstract method
function function_name(){
// set of statements
}
function function_name(arguments){
// set of statements
}
}
Abstract method are like normal methods, without implementation only means no function body and statements, it can also accept arguments.
Abstract class with abstract method only
<?php
abstract class myAbstract{
// abstract method
abstract function add($a,$b);
}
class Math extends myAbstract{
// Implementing abstract class method
function add($a,$b){
return ($a + $b);
}
}
$obj = new Math();
echo $obj->add(20,30);
?>
In above example, class myAbstract is abstract class, With an abstract method named add() which accepts two arguments $a, $b.
- Class Math is a concrete or non-abstract class which extends myAbstract class.
- Therefore, Math has to implement all its abstract methods of myAbstract class.
- In Math, myAbstract class, abstract method add() is implemented and it returns the sum of $a and $b.
Abstract class with abstract and non-abstract methods
<?php
abstract class myAbstract{
// abstract method
abstract function add($a,$b);
//Non-abstract method
function sayHello(){
echo "<br/>"."Hello";
}
}
class Math extends myAbstract{
function add($a,$b){
return ($a + $b);
}
}
$obj = new Math();
echo $obj->add(20,30);
echo $obj->sayHello();
?>
Non-abstract method sayHello() is called using Math class object.