I am trying my best to deliver Object Oriented Concepts of PHP5 in a simple, sequential and understandable way for the every visitor of TutorialChip. This article is also the part of PHP5 OOP series. I am little bit relaxed after a long, professional and scalable coding of Chip Life WordPress theme which is finally the part of WordPress free themes directory.

The theme of this post is to cover the concept of invoking an overridden method in the child class while playing with inheritance.

Invoking an Overridden Method

Recommended Tutorials

I am going to explain the concept of overridden methods by continuing our previous classes which are,

  • Human Class: Parent/Base Class
  • Male: Child/Sub Class
  • Female: Child/Sub Class

You will be familiar with the method of parent class “getName” after reading above recommended tutorials. This method is,

/**
* Get Name
*/

public function getName() {
	$temp = "Name: " . $this->firstName . " " . $this->lastName . "<br />";
	return $temp;
}

Invoking an Overridden Method

The parent keyword can be used with any method that overrides its counterpart in a parent class. When you override a method, you may not wish to obliterate the functionality of the parent but rather extend it. You can achieve this by calling the parent class’s method in the current object’s context.

Let’s explore two examples which will clear the concept of obliteration and extension of parent method.

Overridden Method Example 1 – Extend the Parent method

We will extend the parent method getName in our Male class by invoking an overridden method. Let’s see the code snippet.

/**
* Get Name
* Invoking an Overridden Method
*/

public function getName() {
	$temp = parent::getName();
	$temp .= " An overridden example with parent and child data. ";
	return $temp;
}

Let’s make it simple,

  • We have used the same name of method in our child Male class.
  • We have taken the output of parent method by using parent::getName(); syntax.
  • We have extended the functionality of “getName” method in child Male class, and finally returned to the object.

Overridden Method Example 2 – Obliterate the Parent method

It might be possible that we don’t want to extend the parent method for some reasons. So this example will show you the complete eradication of parent method. Let’s see the code snippet of Female class method, getName.

/**
* Get Name
* Invoking an Overridden Method
*/

public function getName() {
	$temp = " An overridden example with child data only. ";
	return $temp;
}

The concept is same as of our example 1, but we have erased the parent method completely in this case.

I hope you have enjoyed the concept of invoking an overridden method. Don’t Forget to Follow TutorialChip on Twitter or Subscribe to TutorialChip to Get the Latest Updates on Giveaways, Tutorials and More for Free.

One thought

Comments are closed.