Friday, February 21, 2014

PHP Call parent class function inside child class function example




class Person
{
	
	public function whoAmi()
	{
		return 'I am a person';
	}
	
}

class SimplePerson extends Person
{
	
	public function personEnquiry()
	{
		$whoami = parent::whoAmi();
		echo "The person told ".$whoami;
	}
	
}



$person = new SimplePerson();

$person->personEnquiry();

// output is The person told I am a person

In the above example class Person have a function named whoAmi().

we want to call it inside another class that extends person class.

by using parent:: keyword we can access function from its parent class

parent::whoAmi(); line access the whoAmi function that is defined in the Parent class.

No comments:

Post a Comment