CodexBloom - Programming Q&A Platform

PHP 8.1: `get_class()` returns unexpected result when called on an instance created in a closure

👀 Views: 3 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
php php-8.1 closures

I'm working with a strange scenario in PHP 8.1 where the `get_class()` function is returning an unexpected result when I call it on an object instantiated within a closure... I have the following code: ```php class MyClass { public function myMethod() { return function() { $instance = new class() { public function test() { return 'Hello'; } }; return get_class($instance); }; } } $obj = new MyClass(); $closure = $obj->myMethod(); echo $closure(); ``` I expected the output to be the name of the anonymous class, but it returns `__PHP_Incomplete_Class` instead. This is happening even though I have not attempted any serialization or anything that might typically lead to this result. I've checked my PHP configuration and everything seems to be fine. I've also tried using `ReflectionClass` to inspect the class name: ```php $reflection = new ReflectionClass($instance); return $reflection->getName(); ``` However, I still face the same scenario. Could someone explain why this behavior occurs and suggest how to properly retrieve the class name of an instance created in a closure? This is part of a larger API I'm building.