PHP Anonymous classes


Introduction

As th name suggests, anonymous class is the one which doesn't have name. It is meant for one time use, and if one needs to define a class on the fly. Feature of anonymous class has been introduced since PHP 7 version.

Definition of anonymous class lies inside an expression whose result is an object of that class. It is defined with new class syntax as follows

Syntax

<?php
$obj=new class {
   public function sayhello(){
      echo "Hello World";
   }
};
$obj->sayhello();
?>

Anonymous class can perform everything that a normal can i.e. extend another class, implement interface or use trait

In following code, an anonymous class extends parentclass and implements parentinterface

Example

 Live Demo

<?php
class parentclass{
   public function test1(){
      echo "test1 method in parent class
";    } } interface parentinterface{    public function test2(); } $obj=new class() extends parentclass implements parentinterface {    public function test2(){       echo "implements test2 method from interface";    } }; $obj->test1(); $obj->test2(); ?>

Output

The output is as below −

test1 method in parent class
implements test2 method from interface

Nested anonymous class

Anonymous class can be nested inside body of other class method. However, its object doesn't have access to private or protected members of outer class

Example

 Live Demo

<?php
class testclass{
   public function test1(){
      return new class(){
         public function test2(){
            echo "test2 method of nested anonymous class";
         }
      };
   }
}
$obj2=new testclass();
$obj2->test1()->test2();
?>

Output

Above code produces following result −

test2 method of nested anonymous class

Internal name of anonymous class

PHP parser does give a unique name to anonymous class for internal use

Example

 Live Demo

<?php
var_dump(get_class(new class() {} ));
?>

Output

This will produce output similar to following −

string(60) "class@anonymous/home/cg/root/1569997/main.php0x7f1ba68da026"

Updated on: 18-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements