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.

PHP oops Hybrid Inheritance Example



class GrandFather
{
	public function pocketMoney()
	{
		return  'Take this 1000 $';
	}

}


class Father extends GrandFather
{
	public function myIncome()
	{
		echo "My father told ".parent::pocketMoney();
	}
	
	public function myExpense()
	{
		return 'Take this 500 $
'; } } class Elder extends Father { public function myEarning() { echo "Father told me ".parent::myExpense(); } } class Younger extends Father { public function myEarning() { echo "Father told me ".parent::myExpense(); } } $elder = new Elder(); $elder->myEarning(); // output Father told me Take this 500 $ $younger = new Younger(); $younger->myEarning(); // output Father told me Take this 500 $

PHP oops Hierarchical Inheritance Example




class Father
{
	public function pocketMoney()
	{
		return  'Take this 500 $';
	}

}

class Elder extends Father
{
		
	public function myEarning()
	{
		echo "Father told me ".parent::pocketMoney();

	}

}

class Younger extends Father
{
	public function myEarning()
	{
		echo "Father told me ".parent::pocketMoney();

	}

	
}


$elder = new Elder();

$elder->myEarning();  // output Father told me Take this 500 $

$younger = new Younger();

$younger->myEarning();  // output Father told me Take this 500 $