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

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

php new keyword

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 above examples, using the statement:

$obj = new Student();

an object named $obj is created of type Student class. To learn about classes and objects in detail, refer to its separate tutorial.

PHP Online Test


« PHP Tutorial CodesCracker »

Like/Share Us on Facebook 😋