×
Namespaces

Variants
Actions

PHP - Inheritance

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Article
Created: Maveric (25 Jun 2011)
Last edited: hamishwillee (31 Jul 2012)

This article explains the basics of inheritance in PHP.

Introduction

The use of inheritance could be simply put to words creating class B based on class A, without the need of writing what's inside of the class A. Here the class A is called parent class where as class B is child of class A. Whatever class we are going to inherit from, it must always exist.

In the following example we will create a parent class called theAircraft. We will then inherit a child class called theFighter from it.

Example code

For the parent class we will add a public variable "$engines" and one function "startEngines()". The purpose of this function is only to display a message.

When we want to "copy" or "clone" the parent class to the child class, we can do it by defining "extend" in the class declaration. Even though the inheriting child class will be empty, PHP will know it contains what is in the parent class.

<?php
 
class theAircraft {
public $engines = "To make our fighter to fly we need some thrust.";
 
function startEngines() {
echo "To make it off the ground, we need to start the engine(s) first.";
}
 
}
 
class theFighter extends theAircraft {
 
// visually empty class, but will internally contain what is in theAircraft.
 
}
 
// Creates a new object called "myFighter" of the child class "theFighter".
 
$myFighter = new theFighter();
 
// We can now display what is in the variable, because "theFighter" class contains what is in "theAircraft".
 
echo $myFighter -> engines;
 
// And we can launch the function aswell.
 
$myFighter->startEngines();
 
?>

Summary

In the previous example we had a look at how to get all the functionality of another class "copied" - that is, inherited to the other class. This was done by "extending" the class. The child class had inherit everything from the parent class. After this the newly created class could be populated with other variables and functions for further use.

This page was last modified on 31 July 2012, at 10:28.
45 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×