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 block IP addresses in Apache by using regular expressions (regex) in .htaccess

How to check if a user is logged in, inside a blade file?

How to pick what array_intersect function to use in PHP?

How to Extract Query String (from a URL) Into an Associative Array in PHP

How to hide directory listing in .htaccess?

How to sort an array in javascript?

How to select what columns to return when calling ::all()

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

Why should you update APP_URL from from http://localhost?

301 Redirect a single URL in .htaccess to a new location