- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
<?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
<?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
<?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"
- Related Articles
- Anonymous classes in PHP 7?
- Anonymous classes in C++
- PHP Anonymous functions
- What are anonymous inner classes in Java?
- How are anonymous (inner) classes used in Java?
- Creating anonymous objects in PHP
- PHP Autoloading Classes
- How many types of anonymous inner classes are defined in Java?
- PHP Accessing Global classes
- How can we use a diamond operator with anonymous classes in Java 9?
- Access variables from parent scope in anonymous PHP function
- C# Anonymous Methods
- Windows Anonymous Pipe
- Anonymous Methods in C#
- Anonymous object in Java
