Tuesday, 23 July 2019

Creating Objects in PHP and Calling Member Functions

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.
eg:-$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.
Eg:-<?php
class Books{
  public function name()
{
  echo “Drupal book”;
  }
  public function price()
{
  echo “900 Rs/-”;
  }
}
//To create php object we have to use a new operator. Here php object is the object of the Books Class. 
$obj = new Books();
$obj->name();
$obj->price();
?>
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.
eg:-<?php
$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

0 comments

Post a Comment