Overriding: PHP OOP

Advertisement:

Video tutorial to illustrate Overriding in Object Oriented PHP Programming.

Here, we take two class: A and B. Extend class A to class B. Then, define method display() in class A.

Overriding is an object-oriented programming feature that enables a child class to provide different implementation for a method that is already defined and/or implemented in its parent class or one of its parent classes. The overriden method in the child class should have the same name, signature, and parameters as the one in its parent class.

Class B extends Class A

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
< ?php
		class A
		{
			function display()
			{
				echo "Inside Class A";
			}	
		}
 
		class B extends A
		{
 
		}
 
		$obj = new B();
		$obj->display();
?>

Next, redefine the same method display() inside class B too, with a different output.

Redefine method display inside class B

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
< ?php
		class A
		{
			function display()
			{
				echo "Inside Class A";
			}	
		}
 
		class B extends A
		{
			function display()
			{
				echo "Inside Class B";
			}	
		}
 
		$obj = new B();
		$obj->display();
?>

Now, the method inside class B has higher precedence over it’s parent class method.

Invoking parent method using Scope Resolution Operator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
< ?php
		class A
		{
			function display()
			{
				echo "Inside Class A";
			}	
		}
 
		class B extends A
		{
			function display()
			{
    			  parent::display();
			}			
		}
 
		$obj = new B();
		$obj->display();
?>

You can invoke parent method from subclass by using the keyword parent followed by scope resolution operator and the method name.

Overriding: PHP OOP


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=5tcIUn6nbVE [Watch the Video In Full Screen.]



Note:
1. Altering of function definition in the derived class does not alter the function definition in the parent class.
2. You can override both attributes and methods in the subclass.

Advertisements

1 thought on “Overriding: PHP OOP”

Leave a Reply

Your email address will not be published. Required fields are marked *