PHP Override Method

Summary: in this tutorial, you will learn about the PHP overriding method and how to apply it effectively in your script.

Introduction to the PHP overriding method

Method overriding allows a child class to provide a specific implementation of a method already provided by its parent class.

To override a method, you redefine that method in the child class with the same name, parameters, and return type.

The method in the parent class is called overridden method, while the method in the child class is known as the overriding method. The code in the overriding method overrides (or replaces) the code in the overridden method.

PHP will decide which method (overridden or overriding method) to call based on the object used to invoke the method.

  • If an object of the parent class invokes the method, PHP will execute the overridden method.
  • But if an object of the child class invokes the method, PHP will execute the overriding method.

Let’s take an example to understand method overriding better.

The following example defines the Robot class that has one public method greet() and the Android class that inherits the Robot class:

<?php

class Robot
{
	public function greet()
	{
		return 'Hello!';
	}
}

class Android extends Robot
{	
}Code language: HTML, XML (xml)

When you call the greet() method via the Android’s instance, PHP calls the greet() method of the Robot class:

<?php

$android = new Android();
echo $android->greet(); // Hello!Code language: HTML, XML (xml)

This is a typical inheritance scenario.

Sometimes, you want to completely replace the method’s behavior of the parent class with a new one. In this case, you need to override the method of the parent class.

To override a method, you redefine the method in the parent class again in the child class but use a different logic.

The following adds the greet() method to the Android class that returns a different greeting message:

<?php

class Robot
{
	public function greet()
	{
		return 'Hello!';
	}
}

class Android extends Robot
{
	public function greet()
	{
		return 'Hi';
	}
}

$robot = new Robot();

echo $robot->greet(); // Hello

$android = new Android();
echo $android->greet(); // Hi!Code language: HTML, XML (xml)

How it works

  • First, invoke the greet() method of an instance of the Robot class, the greet() method in the Robot class executes.
  • Second, call the greet() method of an instance of the Android class, the greet() method in the Android class executes.

The following class diagram illustrates the relationship between the Robot and Android classes:

Call the overridden method in the overriding method

When you override a method, you will have two versions of the same method: one in the parent class and the other in the child class.

If you call the method of the parent class in the method in the child class, you cannot use $this keyword like this:

<?php

class Android extends Robot
{
	public function greet()
	{
		$greeting = $this->greet();
		return $greeting . ' from Android.';
	}
}Code language: HTML, XML (xml)

The $this->greet() will call itself indefinitely.

To call the greet() method of the Robot class, you need to use the parent with the scope resolution operator (::) like the following:

<?php

class Android extends Robot
{
	public function greet()
	{
		$greeting = parent::greet();
		return $greeting . ' from Android.';
	}
}Code language: HTML, XML (xml)

In this example, the greet() method in the Andoird class calls the greet() method of the Robot class. It concatenates the string returned by the greet() method of the Robot method with a literal string ' from Android.' and returns the concatenated string.

More on PHP overriding method

Suppose that you need to define a new CheckingAccount class that extends the BankAccount class. The following defines the BankAccount class:

<?php

class BankAccount
{
	private $balance;

	public function __construct($amount)
	{
		$this->balance = $amount;
	}

	public function getBalance()
	{
		return $this->balance;
	}

	public function deposit($amount)
	{
		if ($amount > 0) {
			$this->balance += $amount;
		}
		return $this;
	}

	public function withdraw($amount)
	{
		if ($amount > 0 && $amount <= $this->balance) {
			$this->balance -= $amount;
			return true;
		}
		return false;
	}
}Code language: HTML, XML (xml)

The withdraw() method checks if the withdrawal amount is greater than zero and less than or equal to the current balance before deducting it from the balance.

Second, define the CheckingAccount class that inherits the BankAccount class. The CheckingAccount class also has the withdraw() method that overrides the withdraw() method of the BankAccount class:

<?php

class CheckingAccount extends BankAccount
{
	private $minBalance;

	public function __construct($amount, $minBalance)
	{
		if ($amount > 0 && $amount >= $minBalance) {
			parent::__construct($amount);
			$this->minBalance = $minBalance;
		} else {
			throw new InvalidArgumentException('amount must be more than zero and higher than the minimum balance');
		}
	}

	public function withdraw($amount)
	{
		$canWithdraw = $amount > 0 &&
					   $this->getBalance() - $amount > $this->minBalance;

		if ($canWithdraw) {
			parent::withdraw($amount);

			return true;
		}

		return false;
	}
}Code language: HTML, XML (xml)

The withdraw() method in the CheckingAccount class checks the withdrawal amount against the minimum balance before deducting it.

The following class diagram illustrates the relationship between the BankAccount and CheckingAccount classes:

The final method

To prevent the method in the child class from overriding the method in the parent class, you can prefix the method with the final keyword:

public final function methodName() 
{
   //...
}Code language: PHP (php)

The following adds the id() method to the Robot class:

class Robot
{
	public function greet()
	{
		return 'Hello!';
	}

	final public function id()
	{
		return uniqid();
	}
}Code language: PHP (php)

If you attempt to override the id() method from the Android class, you’ll get an error. For example:

class Android extends Robot
{
	public function greet()
	{
		$greeting = parent::greet();

		return $greeting . ' from Andoid.';
	}

	public function id()
	{
		return uniqid('Android-');
	}
}Code language: PHP (php)

Error:

Cannot override final method Robot::id()Code language: PHP (php)

Summary

  • Method overriding allows a child class to define a method that overrides (or replaces) the method already provided by its parent class.
  • Use parent:: to call the overridden method in the overriding method.
  • Use the final method when you don’t want a child class’s method to override a parent class’s method.
Did you find this tutorial useful?