Friday, February 21, 2014

PHP oops Method overriding Example



class Processes
{
	public function process1()
	{
		echo  'I am process 1';
	}

      public function process2()
	{
		echo  'I am process 2';
	}

	public function process3()
	{
		echo  'I am process 3';
	}

      public function startProcess()
	{
		$this->process1();
		$this->process2();
		$this->process3();
	}

}


class ChildProcess extends Processes
{

	public function process2()
	{
		echo  'I am overrided process 2';
	}


}

$process = new Processes();

$process->startProcess();

/* output is

I am process 1
I am process 2
I am process 3

*/


$child = new ChildProcess();
$child->startProcess();

/*
output is 

I am process 1
I am overrided process 2
I am process 3

*/

From the above example,

Processes is a parent class having 4 methods.  method startProcess() display other three methods content.

if we want to override any of the methods we should create a child class and extend which method we want to override.

in the example process2 overrided by child class.

when this line executes $child->startProcess(); , compiler first execute process1 from parent and execute overrided method

pocess2 then control goes to process3.

No comments:

Post a Comment