Moazzam's Ramblings

25Nov/100

PHP Inheritance – Calling parent’s functions in child object

Before I begin, let me just say that I have tested this in PHP 5.2. I don't know if this will work for PHP 5.3. If anyone can confirm that it does, it will be great.

You can do it with parent::someFunctionName(). You can do this from within an overloaded function also. It was confusing for me at first, so I decided to test it out myself. Below is some same code that will help you understand it too.

class SomeParent {
	// we will initialize this variable right here
	private $greeting = 'hello world';
 
	// we will initialize this in the constructor
	private $bye ;
 
	public function __construct() 
	{
		$this->bye = 'Goodbye';     
	}
 
	public function sayHi()
	{
		print $this->$greeting;
	}
 
	public function sayBye()
	{
		print $this->bye;
	}
	public static function saySomething()
	{
		print 'How are you';
	}
}
 
class SomeChild extends SomeParent {
	public function __construct()
	{
		parent::__construct();
	}
 
	/**
	 * Let's see what happens when we call a parent method
	 * from an overloaded method of its child
	 */
	public function sayHi()
	{
		parent::sayHi();
	}
 
	/**
	 * Let's call a parent method from an overloaded method of
	 * its child. But this time we will try to see if it will
	 * work for parent properties that were initialized in the 
	 * parent's constructor
	 */
	public function sayBye()
	{
		parent::sayBye();
	}
	/**
	 * Let's see if calling static methods on the parent works
	 * from an overloaded static method of its child.
	 */
	public static function saySomething()
	{
		parent::saySomething();
	}
}
$obj = new SomeChild();
$obj->sayHi(); // prints hello
$obj->sayBye(); // prints Goodbye
SomeChild::saySomething(); // prints How are you