PHP Basic Tutorial
MySQL Connection
PHP Advanced
An interface in PHP defines a contract that classes must follow. Any class that implements an interface must define all its methods.
✅ Defined using the interface
keyword.
✅ Cannot have properties (only method declarations).
✅ All methods are public by default.
✅ A class can implement multiple interfaces (unlike abstract classes).
✅ Interface methods cannot have implementations (must be defined in the implementing class).
<?php interface InterfaceName { public function someMethod1(); public function someMethod2($name, $color); public function someMethod3() : string; } ?>
Both interfaces and abstract classes are used to define blueprints for other classes, but they have key differences in structure, usage, and flexibility.
Feature |
Interface |
Untitle |
---|---|---|
Definition |
Uses |
Uses |
Method Implementation |
Cannot have method implementations (only method declarations) |
Can have both abstract (no implementation) and concrete (implemented) methods |
Properties (Variables) |
Cannot have properties |
Can have properties |
Method Access Modifiers |
Always |
Can be |
Constructors |
Cannot have constructors |
Can have constructors |
Multiple Inheritance |
A class can implement multiple interfaces |
A class can extend only one abstract class |
Use Case |
Used when multiple unrelated classes need to implement the same behavior |
Used for common functionality among related classes |
Try it yourself
From the example above, let's say that we would like to write software which manages a group of animals. There are actions that all of the animals can do, but each animal does it in its own way.
Using interfaces, we can write some code which can work for all of the animals even if each animal behaves differently:
Try it yourself
1. Define an Interface (Animal
)
Animal
interface declares the makeSound()
method.Animal
must define makeSound()
.2. Implementing Classes (Cat
, Dog
, Mouse
)
Animal
and defines makeSound()
differently.3. Polymorphism: Handling Different Animals in a Loop
makeSound()
on each object, without needing to check its type.