How to use inheritance in php

Post Reply
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

How to use inheritance in php

Post by Saman » Sun Jul 17, 2011 9:43 am

I found a nice example that illustrate the use of inheritance.

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;
	}
}
Likewise, you would be able to write the female class by inheriting the Human class.
User avatar
johnstreak
Posts: 1
Joined: Thu Oct 13, 2011 5:08 pm

Re: How to use inheritance in php

Post by johnstreak » Thu Oct 13, 2011 5:18 pm

Hi,
PHP is most usable programming language today. The websites created in this language are very simple and easy to use.I would like to say thanks for updating the our knowledge of PHP by this post.
Post Reply

Return to “PHP & MySQL”