What are the main differences between an abstract class and an interface in PHP?
sobes.tech AI
Answer from AI
An abstract class can contain both abstract (without implementation) and concrete (with implementation) methods, as well as properties. An interface contains only method declarations without implementation and cannot have properties.
A class can inherit only one abstract class but can implement multiple interfaces.
An abstract class is used to define the basic functionality and structure for a group of related classes. An interface defines a contract (a set of methods) that classes implementing it must fulfill to ensure polymorphism.
In an abstract class, you can define a constructor, but in an interface, you cannot.
When inheriting from an abstract class, the child class must implement all abstract methods of the parent. When implementing an interface, the class must implement all methods declared in the interface.
<?php
// Example of an abstract class
abstract class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function makeSound(); // Abstract method
public function getName() { // Concrete method
return $this->name;
}
}
// Example of an interface
interface CanFly {
public function fly(); // Method without implementation
}
Main differences in the table:
| Feature | Abstract Class | Interface |
|---|---|---|
| Methods | Abstract and concrete | Only abstract |
| Properties | Can be present | Cannot be present |
| Inheritance | Only one class | Multiple interfaces |
| Constructor | Can be present | Cannot be present |
| Implementation | Partial or full | Full (all methods) |
| Purpose | General functionality | Contract, polymorphism |