PHP Inheritance - OOPs
Inheritance allows a class to inherit properties and methods from another class. This helps to reuse code and build relationships between classes.
Inheritance का मतलब है एक class दूसरी class की properties और methods को प्राप्त कर सकती है। इससे कोड reuse किया जाता है।
Example: Single Inheritance
class Employee {
public $name;
public $age;
public $salary;
function setData($name, $age, $salary) {
$this->name = $name;
$this->age = $age;
$this->salary = $salary;
}
}
class Manager extends Employee {
function display() {
echo "Name: $this->name
";
echo "Age: $this->age
";
echo "Salary: $this->salary
";
}
}
$mgr = new Manager();
$mgr->setData("Ravi", 35, 75000);
$mgr->display();
Output:
Name: Ravi
Age: 35
Salary: 75000
Age: 35
Salary: 75000
Example: Multilevel Inheritance
class Employee {
public $name;
public $age;
public $salary;
function setData($name, $age, $salary) {
$this->name = $name;
$this->age = $age;
$this->salary = $salary;
}
}
class Manager extends Employee {
public $department;
function setDepartment($dept) {
$this->department = $dept;
}
}
class SeniorManager extends Manager {
function display() {
echo "Name: $this->name
";
echo "Age: $this->age
";
echo "Salary: $this->salary
";
echo "Department: $this->department
";
}
}
$sm = new SeniorManager();
$sm->setData("Priya", 42, 95000);
$sm->setDepartment("Finance");
$sm->display();
Output:
Name: Priya
Age: 42
Salary: 95000
Department: Finance
Age: 42
Salary: 95000
Department: Finance