An interface in PHP defines a list of methods that a class must implement. It helps organize code by setting clear rules for what a class can do.
0
0
Interface declaration and implementation in PHP
Introduction
When you want different classes to share the same set of methods but have different behaviors.
When you want to make sure certain methods exist in a class without writing their code yet.
When you want to design your code so parts can be swapped easily without changing other parts.
When you want to group classes by what they can do, not by how they do it.
Syntax
PHP
interface InterfaceName { public function methodName1(); public function methodName2($param); } class ClassName implements InterfaceName { public function methodName1() { // code here } public function methodName2($param) { // code here } }
All methods in an interface must be public and cannot have code inside.
A class that implements an interface must write code for all its methods.
Examples
This example shows an interface
Logger with one method log. The class FileLogger implements it by writing the message.PHP
interface Logger { public function log(string $message); } class FileLogger implements Logger { public function log(string $message) { echo "Logging to a file: $message"; } }
Here,
Shape interface requires an area method. The Circle class implements it and calculates the area.PHP
interface Shape { public function area(); } class Circle implements Shape { private float $radius; public function __construct(float $radius) { $this->radius = $radius; } public function area() { return pi() * $this->radius ** 2; } }
Sample Program
This program defines a Vehicle interface with two methods. The Car class implements these methods and prints messages when starting and stopping the engine.
PHP
<?php interface Vehicle { public function startEngine(); public function stopEngine(); } class Car implements Vehicle { public function startEngine() { echo "Car engine started\n"; } public function stopEngine() { echo "Car engine stopped\n"; } } $myCar = new Car(); $myCar->startEngine(); $myCar->stopEngine();
OutputSuccess
Important Notes
Interfaces cannot contain properties or method bodies.
A class can implement multiple interfaces by separating them with commas.
Interfaces help make your code easier to change and test.
Summary
Interfaces define method names without code.
Classes that implement interfaces must write all those methods.
This helps keep code organized and flexible.