PHP Abstract Class - OOPs
An abstract class in PHP is a class that cannot be instantiated directly. It can contain abstract methods which must be implemented in child classes.
It is meant to be inherited by other classes. It may contain abstract methods (which have no body) and regular methods (with full implementation).
You cannot create an object of an abstract class directly.
Why Use Abstract Classes?
Abstract classes allow you to:
- Define a common structure for all subclasses.
- Force child classes to implement specific methods.
- Share default functionality among subclasses.
Abstract class एक ऐसी class होती है जिसे directly object बनाकर use नहीं किया जा सकता। इसमें abstract methods होते हैं जिन्हें child class में implement करना जरूरी होता है।
यह एक base class की तरह होती है जिसमें कुछ methods सिर्फ define किए जाते हैं लेकिन उनका body नहीं होता। उन methods को child class में implement करना पड़ता है।
Example: Abstract Class with Employee
abstract class Employee {
public $name, $age, $salary;
function setData($name, $age, $salary) {
$this->name = $name;
$this->age = $age;
$this->salary = $salary;
}
abstract function display();
}
class Manager extends Employee {
function display() {
echo "Name: $this->name
";
echo "Age: $this->age
";
echo "Salary: $this->salary
";
}
}
$mgr = new Manager();
$mgr->setData("Amit", 40, 88000);
$mgr->display();
Output:
Age: 40
Salary: 88000