PHP Interface - OOPs
An interface in PHP defines a contract for what methods a class should implement. Interfaces do not contain any implementation, only method declarations.
Classes that implement an interface must define all of its methods.
Interfaces support multiple inheritance in PHP (a class can implement multiple interfaces).
Why Use Interfaces?
Interfaces allow you to:
- Enforce consistent method signatures across unrelated classes.
- Support multiple inheritance.
- Provide flexibility and decoupling in large applications.
Interface एक ऐसा structure होता है जिसमें सिर्फ method के नाम define होते हैं, body नहीं होती। इसे implement करने वाली class को उन सभी methods को define करना जरूरी होता है।
PHP में interface multiple inheritance को support करता है, यानी एक class एक से ज्यादा interface को implement कर सकती है।
Example: Interface with Employee
interface Employee {
function setData($name, $age, $salary);
function display();
}
class Developer implements Employee {
public $name, $age, $salary;
public function setData($name, $age, $salary) {
$this->name = $name;
$this->age = $age;
$this->salary = $salary;
}
public function display() {
echo "Name: $this->name
";
echo "Age: $this->age
";
echo "Salary: $this->salary
";
}
}
$dev = new Developer();
$dev->setData("Ravi", 28, 60000);
$dev->display();
Output:
Name: Ravi
Age: 28
Salary: 60000
Age: 28
Salary: 60000