PHP new keyword: Create an Object from a Class

The PHP "new" keyword is used when we need to create a new object from a class. For example:

<?php
   class Student
   {
      public $name = "Lucas";
      public $city = "Amsterdam";
   }
   
   $obj = new Student();
   
   echo "Name: $obj->name";
   echo "<BR>";
   echo "City: $obj->city";
?>

This PHP code defines a class called "Student". The class has two properties, namely "$name" and "$city" which are both initialized to string values of "Lucas" and "Amsterdam" respectively. Then, an object of the class "Student" is created using the "new" keyword and assigned to the variable "$obj".

Finally, the code outputs the values of the object's properties using the "echo" statement. It displays the string "Name: " followed by the value of the "$name" property and then a line break ("<BR>"). After that, it displays the string "City: " followed by the value of the "$city" property.

The output of the above PHP example on the "new" keyword is shown in the snapshot given below:

php new keyword

In other words, we can say that the PHP "new" keyword creates class instances. PHP creates a class-specific object and returns a reference when the new keyword is used.

The above example can also be written in this way:

<?php
   class Student {
      public $name = "Lucas";
      public $city = "Amsterdam"; }
   
   $obj = new Student();
   
   echo "Name: ", $obj->name, "<BR>City: ", $obj->city;
?>

Or

<?php
   class Student {
      public $name = "Lucas";
      public $city = "Amsterdam";
   }
   
   $obj = new Student();
   
   $x = $obj->name;
   $y = $obj->city;
   
   echo "Name: ", $x, "<BR>City: ", $y;
?>

In the above examples, using the statement:

$obj = new Student();

An object named $obj is created of type Student class.

Advantages of the "new" keyword in PHP

Disadvantages of the "new" keyword in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »