• Post category:PHP

How to Create a New Object in PHP

PHP Create a New Object

once we defined our class, then we can create as many objects as we like of that class type. So, In this article, we will see how to create a new object in php
Syntax:

$objectname = new classname;

Example:

class Books{
var $title;
function setTitle($par){
$this->title = $par;
} 
function getTitle(){
echo $this->title;
} }

Here, we have created a class “Books”. If we want to access the functions of this class, so we need to create objects.

Ex:

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

Here, we have created two objects and these objects are independent of each other and they will have their existence separately.

After creating our objects, we wil be able to call member functions related to that object. One member function will be able to process member variables of related objects only.

Note:

  • . When a class member is used in only one member function of a class, it is enough to use that member as %classmember.
  • When a class member is used across many member functions, it is mandatory to access the class members using $this->.
  • Note that no “$” before class member while accessing by this pointer.
  • But have the practice of accessing a class member using this pointer, irrespective of the number of member functions.

Ex:

$physics->setTitle("physics for High school");
$maths->setTitle("Algebra");

Now we call member functions to get the values set by in the above example:

$physics->getTitle();
$maths->getTitle();

Output:

php create new object

Leave a Reply