Home > PHP, PHP Tutorials, PHP5 OOPS Tutorials > PHP5 Tutorial – Inheritance in PHP5

PHP5 Tutorial – Inheritance in PHP5

November 15th, 2007 admin Leave a comment Go to comments

In the tutorial we will understand what is Inheritance in general and how to inherit classes in PHP5.

Definition of Inheritance:

Inheritance is the mechanism of deriving a new class from an existing class. It allows a sub-class / child class to share/inherit the attributes and behaviors of a base-class or parent class. These inherited attributes and behaviors are usually modified by means of extension.







PHP5 Inheritance

To inherit in PHP5, you should use the keyword ‘extends’ in the class definition. In PHP5 only single inheritance is allowed. Look at the example below:

class Person {
	private $name;
	private $address;
 
	public function getName() {
		return $this->name;
	}
}
 
class Customer extends Person {
	private $customer_id;
	private $record_date;
 
	public getCustomerId() {
		return $this->customer_id;
	}
 
	public getCustomerName() {
		return $this->getName();// getName() is in Person
	}
}

In the above example, class Customer extends from the Person class. This means that Customer class is the child class and the Person base class. The child class Customer extends the method getName() and calls it in the getCustomerName() method of the Customer class.

Inheritance and Access Specifiers
You can refer to the Access specifiers tutorial to understand what it means. Let’s understand the use of Access Specifiers with context to Inheritance.

Access specifiers specify the level of access that the outside world (other objects and functions) have on the data members / member functions of the class. Please note that all data members and member functions are public by default.

Lets look at how three access specifiers viz. private, public and protected behave in Inheritance:

1. private

A private access specifier is used to hide data and member functions. A method or data member declared as private can only be accessed by the class itself and neither the outside program nor the derived class can have access to it. Lets look at an example below:

class Customer {
	private $name;
	public $age;
 
	public function __construct($name, $age) {
		$this->name = $name;
		$this->age = $age;
	}
}
 
$c = new Customer("Sunil","28");
echo "Name : " . $c->name; //causes an error

In the above example, the statement;

echo “Name : ” . $c->name;

causes an error as we are trying to access $name that has been declared as a private member variable. We can however access the $age data member without any limitation as its public. We will learn more about public later in this tutorial.

The reason why data members are declared private is to avoid the outside programs to either accidently modify the values without necessary validation. If you make a data member private you should provide accessor/mutator methods to access. Read more about accessor/mutator methods here (You will have to scroll a bit down and reach to “Notes on Accessor and Mutator methods”)

Note: When you define a method as private that method can only be called from within that class and not from outside that is the global level script.

2. public

A public access specifier allows the data members and methods to be access from anywhere in the script. Lets look at an example below:

class Customer {
	private $name;
	public $age;
 
	public function __construct($name, $age) {
		$this->name = $name;
		$this->age = $age;
	}
}
 
$c = new Customer("Sunil","28");
echo "Age : " . $c->age; //prints 28

In the above example, the statement;

echo “Age : ” . $c->;age;

prints 28 on the screen as $age is a public variable and hence can be accessed from anywhere in the script. Please note that if you declare any data member or method without a access specifier it is considered as ‘public’.

3. protected

A protected access specifier allows the derived class to access the data member or member functions of the base class, whereas disallows global access to other objects and functions.

class Person {
	protected $name;
}
 
class Customer extends Person {
	function setName($name) {
		//this works as $name is protected in Person
		$this->name = $name;
	}
}
 
$c1 = new Customer();
$c1->setName("Sunil");
$c1->name = "Sunil"; //this causes error as $name is protected and not public

In the above example, the statement;

$this->name = $name;

in the setName() function is referring to the $name data member of the Person class. This access is only possible because the $name variable has been declared as protected. Had this been private; the above statement would have raised an error. Further, in the statement towards the end;

$c1->name = “Sunil”;

raises an error as $name in the Person class has been declared as protected and not public.

PHP5 Inheritance – Method Overriding
Lets learn how to override methods in PHP5, but before we understand how to override methods in PHP5; lets define method overriding.

Definition of Method Overriding:
Method overriding is when the function of base class is re-defined with the same name, function signature and access specifier (either public or protected) of the derived class.

The reason to override method is to provide additional functionality over and above what has been defined in the base class. Imagine that you have a class by the name of Bird from which you derive two child classes viz. Eagle and Swift. The Bird class has methods defined to eat, fly, etc, but each of the specialized classes viz Eagle and Swift will have its own style of flying and hence would need to override the flying functionality.

Lets look at an example with Bird:

class Bird {
	public function fly() {
		echo "Fly method of Bird Class called";
	}
}
 
class Eagle extends Bird {
	public function fly() {
		echo "Fly method of the Eagle Class called";
	}
}
 
class Swift extends Bird {
	public function fly() {
		echo "Fly method of the Swift Class called";
	}
}
 
$e = new Eagle();
$s = new Swift();
 
$e->fly();
echo "\n";
$s->fly();

Output:
Fly method of the Eagle Class called
Fly method of the Swift Class called

In the above example, we create two objects of class Eagle and Swift. Each of these classes have overridden the method fly() and have provided their own implementation of the fly() method that has been extended from the Bird class. The manner in which they have been extended the Bird class fly() method is not called as both these classes have provided a new functionality for the fly() method.

Another example of function overriding in Inheritance

class Person {
	function calculateAge($dob) {
		echo "calculateAge called of Person Class\n";
	}
 
}
 
class Customer extends Person {
	function calculateAge($dob) {
		echo "calculateAge called of Customer Class\n";
	}
}
 
$c1 = new Customer();
$p1 = new Person();
 
$c1->calculateAge("something");
$p1->calculateAge("something More");

Output:
calculateAge called of Customer Class
calculateAge called of Person Class

PHP5 Inheritance – Invoking parent methods
When you override a method of the base class, it’s functionality is completely hidden unless it has been explicitly invoked from the child class. To invoke a parent class method you should use the keyword parent followed by the scope resolution operator followed by the name of the method as mentioned below:

	parent::function_name();

Look at the example below:

class Person {
	public function showData() {
		echo "This is Person's showData()\n";
	}
}
 
class Customer extends Person{
	public function showData() {
		parent::showData();
		echo "This is Customer's showData()\n";
	}
}
 
$c = new Customer();
$c->showData();

Output:
This is Person’s showData()
This is Customer’s showData()

In the above example, look at the way in which the showData() function in the Customer child class is invoking the the Person parent class’s showData() function. When the program executes the showData() method if the Customer class is called which inturn calls the showData() function of the parent class. After the parent class’s showData() function complets its execution the remaining code in showData() function of the Customer class is executed.

PHP5 Inheritance – Invoking parent Constructor and Destructor
We can get the parent PHP5 constructor and PHP5 Destructor to be invoked in the same way as invoking the parent method, refer to the example below:

class Person{
	public function __construct() {
		echo "This is Person's __construct()\n";
	}
 
	public function __destruct() {
		echo "This is Person's __destruct()\n";
	}
}
 
class Customer extends Person{
	public function __construct() {
		parent::__construct();
		echo "This is Customer's __construct()\n";
	}
 
	public function __destruct() {
		parent::__destruct();
		echo "This is Customer's __destruct()\n";
	}
}
 
$c = new Customer();

Output:
This is Person’s __construct()
This is Customer’s __construct()
This is Person’s __destruct()
This is Customer’s __destruct()

Related Posts on PHP5 Tutorial – Object Oriented Programming (OOPS)

  1. PHP5 Tutorial – Learn to create a PHP5 Class
  2. PHP5 Tutorial – Learn to Create a PHP5 Class Object
  3. PHP5 Tutorial – Defining Attributes of a PHP5 Class
  4. PHP5 Tutorial – Defining Methods of a PHP5 Class
  5. PHP5 Tutorial – Creating a PHP5 Constructor __construct()
  6. PHP5 Tutorial OOPS – Creating a PHP5 Destructor __destruct()
  7. PHP5 Tutorial OOPS – PHP5 Class Access Specifiers – public, private and protected
  8. PHP5 Tutorial – $this variable explained
  9. PHP5 Tutorial – instanceOf Operator Explained
  10. PHP5 Tutorial – Defining Class Constants
  11. PHP5 Tutorial – Magic Methods – __toString() method
  12. PHP5 Tutorial – Magic Methods – __get() and __set()
  13. PHP5 Tutorial – Magic Methods – __isset() and __unset()
  14. PHP5 Tutorial – Magic Methods – __call() method
  15. PHP5 Tutorial – Magic Methods – __autoload() method
  16. PHP5 Tutorial – Magic Methods – __sleep() and __wakeup()
  17. PHP5 Tutorial – Magic Methods – __clone() method




Categories: PHP, PHP Tutorials, PHP5 OOPS Tutorials Tags:

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /home/sunilb/www.sunilb.com/wp-content/plugins/all-in-one-seo-pack/aioseop.class.php:245) in /home/sunilb/www.sunilb.com/wp-content/plugins/mycaptcha/MyCaptcha.php on line 41

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/sunilb/www.sunilb.com/wp-content/plugins/all-in-one-seo-pack/aioseop.class.php:245) in /home/sunilb/www.sunilb.com/wp-content/plugins/mycaptcha/MyCaptcha.php on line 41
  1. Ed Heal
    August 25th, 2009 at 19:56 | #1

    public function __destruct()
    {
    // Some code here for the destructor that
    // might use the parent class
    parent::__destruct(); // Needs to be the last line in the destructor
    }

  2. March 4th, 2010 at 17:55 | #2

    good posting….

  1. No trackbacks yet.
Enter this code to leave comment (Sorry, but bots get me crazy :) )