9

Since PHP7, we have anonymous classes.

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

wpclevel
  • 2,451
  • 3
  • 14
  • 33
  • Out of interest, what are you using Anonymous Classes for? They're pretty interesting, and cool; but (outside of a few specialist libraries) I've not seen any use-cases where they're particularly useful – Mark Baker Jun 08 '16 at 10:54
  • @MarkBaker I need to create an object in a callback quickly and it must implement a certain interface ;-) – wpclevel Jun 08 '16 at 11:06

2 Answers2

12

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());
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

You can try this one: Here

<?php 
class TestClass {}
$anonClass = new class {};

$normalClass = new ReflectionClass('TestClass');
$anonClass  = new ReflectionClass($anonClass);

var_dump($normalClass->isAnonymous());
var_dump($anonClass->isAnonymous());
?>

Output:

bool(false) bool(true)

Mahesh Saini
  • 19
  • 1
  • 4