PHP Class Inheritance With Practical Examples - OOP Interview Questions
Last Updated: March 2, 2024
Inheritance in PHP allows one class (child class) to inherit the properties and methods of another class (parent class). This mechanism is key to promoting code reuse and improving code organization. Here's a straightforward example to illustrate inheritance in PHP
Let's take an example of a banking system to focus on the core concept of inheritance in PHP with just two classes: a general BankAccount class and a derived SavingsAccount class that adds a simple interest feature.
Parent Class: BankAccount
This class includes basic properties such as the account holder's name and balance. It allows for depositing and withdrawing money.
class BankAccount {
public $holderName;
public $balance;
public function __construct($holderName, $balance = 0) {
$this->holderName = $holderName;
$this->balance = $balance;
}
public function deposit($amount) {
$this->balance += $amount;
echo "Deposited: $amount. Balance is now: {$this->balance}.\n";
}
public function withdraw($amount) {
if ($amount <= $this->balance) {
$this->balance -= $amount;
echo "Withdrew: $amount. Balance is now: {$this->balance}.\n";
} else {
echo "Insufficient funds to withdraw $amount.\n";
}
}
}
Child Class: SavingsAccount
The SavingsAccount class inherits from BankAccount and adds a method to apply an annual interest to the balance. The interest rate is a new property specific to the SavingsAccount class.
class SavingsAccount extends BankAccount {
public $interestRate;
public function __construct($holderName, $balance, $interestRate) {
parent::__construct($holderName, $balance);
$this->interestRate = $interestRate;
}
public function applyInterest() {
$interest = $this->balance * ($this->interestRate / 100);
$this->balance += $interest;
echo "Interest: $interest added. New balance: {$this->balance}.\n";
}
}
This is how you can use it, I have commented the steps as this would be easy to understand
// Create a new Savings Account with an initial balance and an interest rate
$savingsAccount = new SavingsAccount("Alex Doe", 1000, 5);
// Deposit money into the account
$savingsAccount->deposit(500); // Balance now: 1500
// Apply interest to the account
$savingsAccount->applyInterest(); // Interest: 75 added. New balance: 1575.
// Withdraw money from the account
$savingsAccount->withdraw(575); // Withdrew: 575. Balance is now: 1000.
Essential PHP Inheritance FAQs for Developers
1. What is inheritance in PHP?
Inheritance is a fundamental concept in Object-Oriented Programming (OOP) where a class (known as a child or derived class) can inherit properties and methods from another class (known as a parent or base class). This mechanism promotes code reuse and hierarchical classifications.
2. How do you implement inheritance in PHP?
Inheritance in PHP is implemented using the extends
keyword. A child class can extend a parent class, thereby inheriting its public and protected properties and methods.
class ParentClass {
// Properties and methods
}
class ChildClass extends ParentClass {
// Additional properties and methods
}
3. Can PHP classes inherit multiple classes?
No, PHP does not support multiple inheritance directly. A class can extend only one other class. However, PHP supports the use of interfaces and traits to achieve similar outcomes.
4. What is the difference between private, protected, and public properties in the context of inheritance?
Public properties and methods are accessible from anywhere, including from derived classes. Protected properties and methods are accessible within the class itself and by inheriting and parent classes. Private properties and methods are only accessible within the class that defines them, not by derived classes.
5. How do you call a parent class's method from a child class in PHP?
You can call a parent class's method from within a child class using the parent
keyword followed by the method name. This is commonly used in overridden methods.
class ParentClass {
public function sayHello() {
echo "Hello from ParentClass";
}
}
class ChildClass extends ParentClass {
public function sayHello() {
parent::sayHello();
echo " and Hello from ChildClass";
}
}
$child = new ChildClass();
$child->sayHello(); // Outputs: Hello from ParentClass and Hello from ChildClass
6. What is constructor inheritance in PHP?
Constructor inheritance refers to the way constructors are handled in the context of inheritance. If a child class does not define its own constructor, PHP will automatically call the parent class's constructor if one is defined.
7. Can a child class override a parent class's property or method?
Yes, a child class can override a parent class's methods (except for final methods) and properties. Overriding allows the child class to provide a specific implementation of a method or property already defined in the parent class.
8. Explain the final
keyword in the context of PHP inheritance.
The final
keyword prevents class inheritance and method overriding. If a class is defined as final, it cannot be extended. If a method is defined as final, it cannot be overridden by child classes.
9. What is method overriding in PHP?
Method overriding occurs when a child class redefines a method that it inherited from a parent class. The overridden method in the child class replaces the parent class's version when called on an instance of the child class.
10. How does PHP handle method overloading and method overriding?
Method Overriding: PHP supports method overriding, where a child class redefines an inherited method from the parent class. Method Overloading: PHP does not support traditional method overloading (having multiple methods with the same name but different parameters). Instead, PHP utilizes dynamic features and magic methods like __call
for similar behaviors.