How to use Anonymous classes in PHP 7?

PHP: How to use Anonymous classes in PHP 7?

PHP 7 introduced a new feature of Anonymous classes. Here is how to use them.

  1. // Pre PHP 7 code
  2. class Logger
  3. {
  4.     public function log($msg)
  5.     {
  6.         echo $msg;
  7.     }
  8. }
  9.  
  10. $util->setLogger(new Logger());
  11.  
  12. // PHP 7+ code
  13. $util->setLogger(new class {
  14.     public function log($msg)
  15.     {
  16.         echo $msg;
  17.     }
  18. });

They are great for mocking, as you can easily write quick classes to do their purposes for a test.

You cannot define an anonymous class without instantiating it at the same time. I.e. when you create an anonymous class, it is instantiated at the same time.

They can extend other classes and use interfaces too.

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to use Anonymous classes in PHP 7?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the PHP language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to use Anonymous classes in PHP 7?

How to sort an array in javascript?

What are the SPL data structures

How to convert between types in JS?

What are Template literals (Template strings) in JS?

What is the loop variable in a @foreach loop in Blade?

What is Bubble sort, and how to write an implementation of it in PHP

How to set up custom error pages in .htaccess for your Apache server (ErrorDocument)

How to make Apache force download of files (in .htaccess)

What are route patterns in Laravel?