PHP | Objects

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.


$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:


   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 */  


A constructor is a key concept in object oriented programming in PHP. Constructor in PHP is special type of function of a class which is automatically executed as any object of that class is created or instantiated.
Constructor is also called magic function because in PHP, magic methods usually start with two underscore characters.

Below is the sample code for the implementation of constructors:
Program for Constructors:

class GeeksforGeeks
    public $Geek_name = "GeeksforGeeks";
    // Constructor is being implemented.
    public function __construct($Geek_name)
        $this->Geek_name = $Geek_name;
// now constructor is called automatically 
// because we have initialized the object
// or class Bird.
$Geek = new GeeksforGeeks("GeeksforGeeks"); 
echo $Geek->Geek_name;



This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment



load comments

Subscribe to Our Newsletter