home

Php Inheritance Tutorial


Inherintance is one of the most important dynamics in OOP.

When you need to create multiple objects that share some of their members (properties or methods) but not others, you do not want to duplicate those members again and again.

The solution is inheritance:

For this example we will use again the Person class from previous tutorial, then we will create a Student class that will inherit from Person.

Step 1. Person class:

<?php #Inheritance.php

class Person
{
public $numberOfLegs = 2;

public function __construct($name = 'unknown', $surname = 'unknown')
{
$this->name = $name;
$this->surname = $surname;
}//end constructor

public function introduce()
{
echo "<p>Hello, my full name is <strong>
$this->name $this->surname</strong>.</p>";
echo "<p>If you are interested,
I can tell you I have $this->numberOfLegs legs.</p>";
}//end introduce

}//end Person

?>

Please note the use of the public keyword. Public is the default visibility for members, nevertheless, it is good practice to write it explicitely.

Step 2. Student class extends Person:

<?php #Inheritance.php

class Person
{
public $numberOfLegs = 2;

public function __construct($name = 'unknown', $surname = 'unknown')
{
$this->name = $name;
$this->surname = $surname;
}//end constructor

public function introduce()
{
echo "<p>Hello, my full name is <strong>
$this->name $this->surname</strong>.</p>";
echo "<p>If you are interested,
I can tell you I have $this->numberOfLegs legs.</p>";
}//end introduce

}//end Person

/* using the keyword EXTENDS to make Student inherit from Person */
class Student extends Person
{
public function __construct($name = 'unknown',
$surname = 'unknown',
$id = 0,
$topic = 'IT')
{
//ALWAYS call the parent constructor
//from a derived class

parent::__construct($name, $surname);
$this->id = $id;
$this->topic = $topic;
}//end constructor

public function identify()
{
echo "<p>My student id is <strong>$this->id</strong>,
and I am studying <strong>$this->topic</strong></p>";
}//end identify

}//end Student

//creating a new instance of STUDENT called 'bob'
$b = new Student('Bob', 'Robertson', 15017, 'PHP');

//using a Student method
$b->identify();

//using a method inherited from Person
$b->introduce();


/*
My student id is 15017, and I am studying PHP
Hello, my full name is Bob Robertson.
If you are interested, I can tell you I have 2 legs.
*/

?>

Please note:

 


Content on this page requires a newer version of Adobe Flash Player.

Get Adobe Flash player

all rights reseverd by Cramerz.com©. web development company " web design company DotPeak. Digital Agency hostingby HostBay
all contents on cramerz are the property of Cramerz.com. web design courses