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 force SSL in Apache's .htaccess?

How to block IP addresses in Apache by using regular expressions (regex) in .htaccess

How to add comments in PHP

How to block access to certain referrers in Apache using .htaccess

How to generate an array for a dropdown (with ['key' => 'value']) suitable for a dropdown, from a Laravel collection of Eloquent objects?

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

How to install jpegtran for Linux CentOS

How to add the default charset to UTF-8 in .htaccess

What does 'final class' and 'final function' (final method) mean in PHP?

PHP Date commonly used formats