Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect an instance of an anonymous class?

Since PHP7, we have anonymous classes.

How can we know if an $instance is an instance of an anonymous class?

like image 908
dan9vu Avatar asked Jun 08 '16 10:06

dan9vu


People also ask

How do you test an anonymous class?

If you feel the need to test the behavior of your anonymous class move it outside of the publishRequest method, make it either a top level class or a static class in the class containing your publishRequest method.

Can an anonymous class be instantiated?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

How do you call an anonymous class in Java?

Object = new Example() { public void display() { System. out. println("Anonymous class overrides the method display()."); } }; Here, an object of the anonymous class is created dynamically when we need to override the display() method.

Can Anonymous classes be private?

3.12. An anonymous class cannot define any static fields, methods, or classes, except for staticfinal constants. Interfaces cannot be defined anonymously, since there is no way to implement an interface without a name. Also, like local classes, anonymous classes cannot be public, private, protected, or static.


1 Answers

Using Reflection

$instance = new class {};

$testInstance = new ReflectionClass($instance);
var_dump($testInstance->isAnonymous());

EDIT

Of course, given that you must be running PHP7 for anonymous classes anyway, wrap it up into a one-liner

var_dump((new ReflectionClass($instance))->isAnonymous());
like image 129
Mark Baker Avatar answered Oct 20 '22 10:10

Mark Baker