PHP Class Tutorial (Simple class & Inheritant Class)

person Jason Huangaccess_time September 25, 2009

PART I: Class Introduction

I am going to show the simplest class in PHP.

(See the embedded comments for detail. It’s very easy to understand.)


This is the php class code (filename is contact_info.php)

class contact_info
{
  /* declare some class properties as variables */
  var $name;
  var $phone_number;
  var $note;
 
  /* Constructor is simply a function with same name as the class */
  public function contact_info($name)
  {
	$this->name = $name;
  }
 
  /* To assign a value to the class variable - use $this->
 */
  /* NOTE: the variablename when use in $this->, does NOT use the $ in front of variable name */
  public function set_phone_number($phone_number)
  {
	$this->phone_number = $phone_number;
  }
 
  public function set_note($note)
  {
	$this->note = $note;
  }
 
  /* function print out the contact detail information by appending the value of class variables */
  public function print_contact_info()
  {
	$output = "Name is: ".  $this->name ."
". "Phone Number is: ". $this->phone_number. "
". "Note: ".$this->note;
	return $output;
  }
} //end of clasas

This is the code that uses the class: (file name is test_contact_info.php)

/* this tests the contact_info class */
 
/*use include to get all the class definition code */
include ("contact_info.php");
 
/* because the class code is included, now we could declare a new contact_info class object */
$my_contact = new contact_info("Jason");    /* this calls the constructor and pass name to the class object */
 
/* now we set some information using the class contact_info's class functions */
/* the function sets the value for class variables phone_number & name */
$my_contact->set_phone_number("888-999-1111");
$my_contact->set_note("Jason is a great coder and designer.");
 
/* call the class function to print out the contact information */
echo $my_contact->print_contact_info();


The output of running the test_contact_info.php file should be:

Name is: Jason
Phone Number is: 888-999-1111
Note: Jason is a great coder and designer.


Download source code file here: php_class_example

to run, just simply extract to your webserver, and call the test_contac_info.php file in your browser.


PART II: Class Inheritance
(Overwriting of function, Calling Parent Class Function)

This simple tutorial is for showing how class inheritance works in PHP and also provide a simple Object Oriented Programming (OOP) concept.

To put things simply, class inheritance means a class can be inherited by a child class. A child class would inherit all the variables & functions the parent class has. Plus a child class can have its own specific variables & its own functions, it can overwrite the parent class’ function as well.

For example, you can have a parent class called “PEOPLE”, then you can have child class that is inherited called “MAN”, or “WOMAN”. Since man & woman is both type of people.

In the following simple example, I define a child class inherit from class “contact_info” in the previous tutorial. The child class called “business_contact_info” inherits all the variables & functions from contact_info, it also has a variable “company” defined which is only unique to child class “business_contact_info”, this child class overwrites the print_contact_info() function (now prints also the company name).

In the example, I also show how to call the parent class’ functions in a child class. For example, I overwrite the constructor function of class “contact_info” with specific constructor for the child class “business_contact_info”. In the “business_contact_info” constructor function, I call the constructor function of “contact_info” to assign the $name variable.

To call a function defined in parent class. Simply use the syntax [class_name]::[function_name] ([parameters]).


The file: “business_contact_info.php“:

//need to include parent class to define the parent class
include "contact_info.php";
 
//To inherit from a class, simply add extends 
 
/* a child class would automatically inherits all the class variables &
   class functions defined in the parent class. Therefore, business_contact_info has
   all the class variables & functions in the parent class contact_info   */
class business_contact_info extends contact_info
{
	//additional class variables only in this class
	var $company;
	var $title;
 
	/*Ovewriting the constructor function
	To set a title for when creating a new business_contact
	*/
	public function business_contact_info($name, $title)
	{
		/* name is pass along over to the parent class contact_class
		then the title is set in the business_contact_info class. 
 
		To call a parent class's function, just use:
		[Parent ClassName]::[Parent class Function Name] (whatever parameter)
		*/
 
		contact_info::contact_info($name);
 
		$this->title = $title;
	}
 
	public function set_company($company)
	{
		$this->company = $company;
	}
 
	/* To prevent a child class from overwriting a parent class's function
	simply put "final" in the parent's function definition
	For example: to prevent overwrite of function print_contact_info()
	in parent class contact_info. define the function in parent class contact_info as:
	final function print_contact_info() ...
	*/
 
	/* overwriting a function */
	/* in PHP, to overwrite a function that is defined in parent class.
	simply define a function with the same name in the child class. */
	public function print_contact_info()
	{
		$output = "Name is: ".  $this->name ."
".
			       "Phone Number is: ". $this->phone_number. "
".
				   "Company name: ".$this->company. "
".
				   "Title: ".$this->title. "
".
				   "Note: ".$this->note;
 
		return $output;
	}
 
} //end of class

Here is the parent class contact_info.php:

class contact_info
{
  /* declare some class properties as variables */
  var $name;
  var $phone_number;
  var $note;
 
  /* Constructor is simply a function with same name as the class */
  public function contact_info($name)
  {
	$this->name = $name;
  }
 
  /* To assign a value to the class variable - use $this->
 */
  /* NOTE: the variablename when use in $this->, does NOT use the $ in front of variable name */
  public function set_phone_number($phone_number)
  {
	$this->phone_number = $phone_number;
  }
 
  public function set_note($note)
  {
	$this->note = $note;
  }
 
  /* function print out the contact detail information by appending the value of class variables */
  public function print_contact_info()
  {
	$output = "Name is: ".  $this->name ."
". "Phone Number is: ". $this->phone_number. "
". "Note: ".$this->note;
	return $output;
  }
} //end of class

The file “test_business_contact_info.php” shows how to use the inherited class:

include "business_contact_info.php";
 
$my_biz_contact = new business_contact_info("Jason", "Software Engineer");
$my_biz_contact->set_phone_number("888-999-1111");
$my_biz_contact->set_note("Jason is a great coder and designer.");
$my_biz_contact->set_company("MonkeyCanCode.com");
 
echo $my_biz_contact->print_contact_info();

The output of the code:

Name is: Jason
Phone Number is: 888-999-1111
Company: MonkeyCanCode.com
Title: Software Engineer
Note: Jason is a great coder and designer.

Download all the source code files here: inherit_class_example

Comments

  1. $this-> what is the use of this line ,cant we just directly use $this->name=$name inside a function.

  2. var $name;
    var $phone_number;
    var $note;

    Those 3 variables are defined as a class variable, which stores values for a specific instance of the class. For example, I can create 2 instances of class contact_info. Contact_info_1 & contact_info_2. Contact_info_1’s name could be “Jason”, Contact_info_2’s name variable could be “Mike”. They are 2 separate instances of the class / object.

    $this simply refers to the class variable of the calling instances.

    In the case of code I shown:
    If I do: $contact_info_1 = new contact_info(“Jason”),
    The code goes to the class constructor function:
    public function contact_info($name)
    {
    $this->name = $name;
    }

    which then set the $name class variable for this instance to be “Jason”.
    $this->name sets the class variable $name for this instance to “Jason”.

  3. Thanks, good tutorial

  4. Great php class information for beginners in php thanks for sharing it with us …

  5. Alfonso Fernandez

    Thanks for the tutorial.
    helped me a lot to understand classes!

  6. You will be missed.The one place where as a venue and fan I could search by
    what ever perimeters I chose .Good Luck with your future endeavors.

    Best naturals

  7. Thanks alot, veryyy good tutorial

  8. ahaha! wow! now i finally understand how inherit works in php class! sorry i am a newbie 🙂 php is like a beautiful girl! so attractive and challenging! 🙂

  9. Mohamed Minta

    Really helpful, thank you so much. I am leading a php project that called NOMS if people wnat to practice their knowledge in this project they are welcome. Just send me a message to montariva@gmail.com and subject: NOMS project.

  10. Yogesh Jalkote

    Great example which give php class information for beginners, thanks for sharing it with us …

  11. ssssssssssssssssssssssss

  12. Very Helpful……!!Thank you

  13. yeah.. thakx for sharing.. veyi veyi help full tuts… 😉

  14. Thank you so much……………. you are fully clear my all dotes about class and function. For visit my site Click Here

  15. bm. bj;lj

  16. h oipoip io

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>