pTutorial

New way to learn PHP

PHP 5 Inheritance

Inheritance

Inheritance is a concept in which one object acquires all the properties and behaviour of super class or parent class and also add some extra properties and behaviour.

What is inheritance?

Inheritance is just a programming approach. That is used for code reusability. If you inherit any class, all the properties and behaviour of this class available for child class. The class that inherits feature of another class is called child class and a class that is being inherited is called the parent class of super class.


Note: You can create any number of the child class or derived class from a single parent class and each class can have its own properties and method and by default parent class properties and method.

.

Mainly inheritance is used for code reusability.

Super class & Child class

Child class is a class that inherits the class called child class and a class that inherited to the child class called super class or parent class.

To define a child class, simply use the extends keyword together with the name of the parent class.

Note: Super classes are also known as parent class or base class. Similarly, child classes are also called sub class or derived class.

Syntax of inherit class

class super_class_name
{

}


class child_class_name extends super_class_name
{
class definition goes here
}

Example

<?php

class Student 
{
	
	public function get()
	{
	echo "This is parent class
" ; } } class Administrator extends Student{ public function post() { echo "This is child class
"; echo "All properties "; } } $u = new Administrator(); $u->get(); $u->post(); ?>

Output

This is parent class
This is child class
All properties

Student and Administrator are names of class where Student is the parent class of Administrator class. After extending the Student class by the Administrator class, all the property and method of the student class are available in Administrator class, shown in the above example.

Download Source script



Example

<?php

class Student 
{
	public $name= "John";
	public function get()
	{
	echo "This is parent class
" ; echo $this->name; } } class Administrator extends Student{ public function post() { echo "This is child class
"; echo "All properties
"; } } $u = new Administrator(); $u->get(); $u->name="Mr. Brown"; $u->post(); echo $u->name; ?>

Output

This is parent class
JohnThis is child class
All properties
Mr. Brown

You can easily access the property of the parent class as shown in the line number 25.

Download Source Script

Note: PHP does not support multiple inheritance like Java, its provide facility to achieve multiple inheritance by using interfaces.


QUOTES OF THE DAY

We live in this world when we love it.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER