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.

FeatureAbstract classInterface
Keywordabstract class and extendsinterface and implements
Method with codeYesNo, only method names
PropertiesYesNo (only constants)
InheritanceA class can extend only oneA class can implement many
Method visibilitypublic, protected or privatepublic only
Best used forSharing common code between related classesGiving 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.