Quantcast
Channel: class – Monkey Can Code
Viewing all articles
Browse latest Browse all 3

1. PHP Class Introduction

$
0
0

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.


Viewing all articles
Browse latest Browse all 3

Trending Articles