What is Inheritance?
Inheritance is the means by which one or more classes can be derived from a base class. A class that inherits from another is said to be a subclass of it.
This relationship is often described in terms of parents and children. A child class is derived from and inherits characteristics from the parent. These characteristics consist of both properties and methods.
Classes
We will end up following three classes at the end of PHP5 Class Inheritance Basics.
Human Class: Parent/Base Class
Male: Child/Sub Class
Human Class
Code: Select all
/**
* Inheritance Basics
* Class Human (Base/Parent Class)
*/
class Human {
/**
* Class Properties
*/
public $firstName;
public $lastName;
public $gender;
public $skeleton;
/**
* Class Methods
*/
/**
* Class Constructor
*/
public function __construct( $firstName = "First Name", $lastName = "Last Name" ) {
$this->firstName = $firstName;
$this->lastName = $lastName;
}
/**
* Get Name
*/
public function getName() {
$temp = "Name: " . $this->firstName . " " . $this->lastName . "<br />";
return $temp;
}
}
Male Class
Code: Select all
/**
* Inheritance Basics
* Class Male (Subclass/Child Class)
*/
class Male extends Human {
/**
* Class Methods
*/
/**
* Get Gender
*/
public function getGender() {
$temp = "Gender: Male" . "<br />";
$this->gender = $temp;
return $this->gender;
}
/**
* Get Skeleton
*/
public function getSkeleton() {
$temp = "Simple text";
$this->skeleton = $temp;
return $this->skeleton;
}
}