Method Overriding in PHP: Understanding Concepts with a Practical Example

Last Updated: March 2, 2024


Understanding Method Overriding in PHP with a Practical Example

In object-oriented programming, the concept of method overriding allows a subclass to provide a specific implementation of a method that is already defined in its parent class. This is a fundamental feature in many programming languages, including PHP, as it enables polymorphism. Today, we'll dive into a simple yet illustrative example of method overriding in PHP using a bank account scenario.

The Basic Setup

We start with a basic class named BankAccount. This class has a single method called getBalance() which, in a real-world scenario, might connect to a database or perform some calculation to return the balance of a bank account. However, for simplicity, our getBalance() method in the BankAccount class just returns a static string indicating it's returning a balance from the "Parent Class".

class BankAccount {
    public function getBalance() {
        return "Balance from Parent Class 100";
    }
}

Extending the Class

Next, we introduce a subclass named SavingsAccount that extends BankAccount. The purpose of this subclass is to represent a more specific type of bank account, which might have different behaviors or properties than a generic bank account.

Initially, our SavingsAccount class does not have its own getBalance() method. So, if we create an instance of SavingsAccount and call getBalance(), it would use the method from its parent class, BankAccount, returning the balance as specified in the parent class.

Overriding the Method

The real power of method overriding becomes apparent when we decide that the SavingsAccount class should have its own implementation of the getBalance() method. By simply defining a getBalance() method within the SavingsAccount class, we override the parent class's version of the method.

class SavingsAccount extends BankAccount {
    // This function overrides the parent function
    public function getBalance() {
        return "Balance from Child Class 100";
    }
}

The Result

With the overridden getBalance() method in place within the SavingsAccount class, creating an instance of SavingsAccount and calling its getBalance() method now returns the string "Balance from Child Class 100", demonstrating that the child class's version of the method is being used instead of the parent class's version.

$savings = new SavingsAccount();
echo $savings->getBalance();