简体   繁体   中英

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?

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());

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM