Class and Object in PHP

The general form for defining a new class in PHP is as follows −

<?php
	class phpClass {
		var $var1;
		var $var2 = "constant string";
		function myfunc ($arg1, $arg2) {
			[..]
		}
		[..]
	}
?>

Here is the description of each line −

  • The special form class, followed by the name of the class that you want to define.
  • A set of braces enclosing any number of variable declarations and function definitions.
  • Variable declarations start with the special form var, which is followed by a conventional $ variable name; they may also have an initial assignment to a constant value.
  • Function definitions look much like standalone PHP functions but are local to the class and will be used to set and access object data.

Example

Here is an example which defines a class of Books type −

<?php
class Books {
	/* Member variables */
	var $price;
	var $title;
	/* Member functions */
	function setPrice($par){
		$this->price = $par;
	}
								,
	function getPrice(){
		echo $this->price ."<br/>";
	}
	function setTitle($par){
		$this->title = $par;
	}
	function getTitle(){
		echo $this->title ." <br/>";
	}
}
?>

The variable $this is a special variable and it refers to the same object ie. itself.

Creating Objects in PHP

Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using new operator.

$physics = new Books; 
$maths = new Books; 
$chemistry = new Books; 

Here we have created three objects and these objects are independent of each other and they will have their existence separately. Next we will see how to access member function and process member variables.

Calling Member Functions

After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only.

Following example shows how to set title and prices for the three books by calling member functions.

$physics->setTitle( "Physics for High School" ); 
$chemistry->setTitle( "Advanced Chemistry" ); 
$maths->setTitle( "Algebra" );
$physics->setPrice( 10 ); 
$chemistry->setPrice( 15 ); 
$maths->setPrice( 7 ); 

Now you call another member functions to get the values set by in above example −

$physics->getTitle(); 
$chemistry->getTitle(); 
$maths->getTitle(); 
$physics->getPrice(); 
$chemistry->getPrice(); 
$maths->getPrice(); 
This will produce the following result − 
Physics for High School 
Advanced Chemistry 
Algebra 
10 
15 
7