1. PHP Class Introduction

person Jason Huangfolder_openCode, PHPlocal_offer, , access_time September 23, 2009

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_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.


  1. I’m a extended time watcher and I just thought I’d drop by and say howdy there for the extremely 1st time.

    I critically get pleasure from your posts. Thanks
    You are my role designs. Thanks for your write-up

  2. Thanks in support of sharing such a pleasant thought,
    article is pleasant, thats why i have read it fully

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>