Object in PHP
An Object is an individual instance of the data structure defined by a class. We define a class once and then make many objects that belong to it. Objects are also known as instances.
Creating an Object:
Following is an example of how to create object using new operator.
class Book { // Members of class Book } // Creating three objects of book $physics = new Books; $maths = new Books; $chemistry = new Books;
Member Functions:
After creating our objects, we can call member functions related to that object. A member function typically accesses members of current object only.
Example:
$physics->setTitle( \"Physics for High School\" ); $chemistry->setTitle( \"Advanced Chemistry\" ); $maths->setTitle( \"Algebra\" ); $physics->setPrice( 10 ); $chemistry->setPrice( 15 ); $maths->setPrice( 7 );
The following syntax used are for the following program elaborated in the example given below:
Example:
<?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>\" ;
}
}
/* Creating New object using \"new\" operator */
$maths = new Books;
/* Setting title and prices for the object */
$maths->setTitle( \"Algebra\" );
$maths->setPrice( 7 );
/* Calling Member Functions */
$maths->getTitle();
$maths->getPrice();
?>