Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous classes in PHP 7

Where can i use and should i use anonymous classes that are presented in PHP 7 ? I can't find a use case for them.

$message = (new class() implements Message { public function getText() { return "Message"; }}); 
like image 579
Eligijus Avatar asked Jul 15 '15 14:07

Eligijus


People also ask

What are anonymous classes in PHP?

Anonymous classes ¶ Anonymous classes are useful when simple, one-off objects need to be created. All objects created by the same anonymous class declaration are instances of that very class. Note: Note that anonymous classes are assigned a name by the engine, as demonstrated in the following example.

Does PHP support anonymous classes?

In PHP, an anonymous class is a useful way to implement a class without defining it. These are available from PHP 5.3 onwards. Anonymous classes are useful because: They are not associated with a name.

What is the meaning of anonymous class?

An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final. Like a nested class, a declaration of a type (such as a variable) in an anonymous class shadows any other declarations in the enclosing scope that have the same name.

Can anonymous classes have constructors PHP?

PHP Classes and Objects Anonymous Classes Anonymous classes were introduced into PHP 7 to enable for quick one-off objects to be easily created. They can take constructor arguments, extend other classes, implement interfaces, and use traits just like normal classes can.


2 Answers

You can find the information you are looking for here, where the RFC is presented.

The key points of the section "Use cases" are the following:

  • Mocking tests becomes easy as pie. Create on-the-fly implementations for interfaces, avoiding using complex mocking APIs.
  • Keep usage of these classes outside the scope they are defined in
  • Avoid hitting the autoloader for trivial implementations
like image 156
marcosh Avatar answered Oct 03 '22 03:10

marcosh


I also found this useful when writing unit tests for traits so you can test only the trait method i.e.:

trait MyTrait  {     public method foo(): string     {         return 'foo';     } } ... public function setUp(): void {     $this->testObject = (new class() {         use MyTrait;     }); } public function testFoo(): void {     $this->assertEquals('foo', $this->testObject->foo()); } 
like image 38
WOpo Avatar answered Oct 03 '22 04:10

WOpo