What is the difference between abstract class and interface in PHP?
Both abstract class and interface are used to force child classes to follow a structure. But they are used for different purposes.
An abstract class is a partly built class. It can have normal methods with code and abstract methods without code. An interface is only a contract: it lists the methods that a class must have.
| Feature | Abstract class | Interface |
|---|---|---|
| Keyword | abstract class and extends | interface and implements |
| Method with code | Yes | No, only method names |
| Properties | Yes | No (only constants) |
| Inheritance | A class can extend only one | A class can implement many |
| Method visibility | public, protected or private | public only |
| Best used for | Sharing common code between related classes | Giving same rules to unrelated classes |
<?php
abstract class Shape {
abstract public function area();
public function describe() {
return "Area is " . $this->area();
}
}
class Square extends Shape {
private $side;
public function __construct($side) {
$this->side = $side;
}
public function area() {
return $this->side * $this->side;
}
}
$sq = new Square(4);
echo $sq->describe();
?>
Output:
Tutorials Class - Output Window
Area is 16
You can not create an object of an abstract class or an interface directly. Only the child class that completes all methods can be used to create objects.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |