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:
- step one: you create a class with the shared members
- step two: you create other classes that will extend the first one. They will automatically have all the members of their parent class (the class they extend), plus some other different members on their own.
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:
- PARENT is a keyword that allows you to access the class you are extending
- to access a member of a class you use "::", while to access a member of an object you use "->"

