Creating anonymous objects in PHP

PHPServer Side ProgrammingProgramming

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.

Example

 Live Demo

<?php
   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);
?>

Output

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.

raja
Published on 27-Dec-2019 12:44:17
Advertisements