Open In App

PHP | Objects

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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 Books {
   // Members of class Books
}

// Creating three objects of Books
$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();
?>


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




<?php
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;
?>


Output:

GeeksforGeeks


Last Updated : 25 Jul, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads