1. Understanding Inheritance
Inheritance allows a child class to inherit properties and methods from a parent class using the extends keyword. This promotes DRY (Don't Repeat Yourself) architecture.
name}, Email: {$this->email}";
}
}
// Derived Class (Child)
class Teacher extends Member {
public function __construct(
string $name,
string $email,
private string $subject
) {
// Call parent constructor
parent::__construct($name, $email);
}
// Method Overriding
public function getProfile(): string {
return parent::getProfile() . ", Subject: {$this->subject}";
}
}
$teacher = new Teacher("Dr. Rajesh Gupta", "rajesh@cbt.com", "Mathematics");
echo $teacher->getProfile();
2. The parent:: Keyword
The parent:: scope resolution operator enables a child class method to invoke the implementation of the overridden parent method, extending rather than replacing the parent's logic.
3. Preventing Overriding: final Keyword
Prepending final to a class or method prevents subclasses from extending the class or overriding the method:
4. Abstract Classes and Interfaces
- Abstract Class: A class containing at least one abstract method (declared without implementation) that all subclasses must implement.
- Interface: A pure contract specifying which methods a class must implement using
implements.