Creating anonymous objects in PHP

Beginning from PHP version 7, it has been made possible to create anonymous classes. Every object in PHP is associated with a class. The anonymous classes can be instantiated to create objects.


 Live Demo

   class my_sample_class {}
   $obj = new class extends my_sample_class {};
   echo "Does the instance belong to parent class? = " ;
   echo var_dump($obj instanceof my_sample_class);


Does the instance belong to parent class? = bool(true)

In the above code, a parent class (my_sample_class) has been created, and it has been instantiated with a child class (new class) that inherits from the parent class.

We are checking if the instance belongs to the parent class. Since the child class is an extension of the parent class, it returns True as output.

Updated on: 27-Dec-2019


Kickstart Your Career

Get certified by completing the course

Get Started