PHP 8.1: advanced patterns with Object Destructuring in Combination with Array Functions
I've been banging my head against this for hours. I tried several approaches but none seem to work. I've looked through the documentation and I'm still confused about I'm experiencing an scenario with object destructuring in PHP 8.1 when used alongside array functions like `array_map()`. I have a class `User` that implements `JsonSerializable` to return a specific structure when serialized. The question arises when I try to destructure properties from an array of `User` objects inside an `array_map` callback. Instead of getting the expected array of user data, I receive an behavior indicating that the object want to be accessed. Hereβs a simplified version of my code: ```php class User implements JsonSerializable { public string $name; public int $age; public function __construct(string $name, int $age) { $this->name = $name; $this->age = $age; } public function jsonSerialize() { return ['name' => $this->name, 'age' => $this->age]; } } $users = [ new User('Alice', 30), new User('Bob', 25), ]; $userData = array_map(fn($user) => [ 'name' => $user->name, 'age' => $user->age ], $users); print_r($userData); ``` When I run this code, I expect `$userData` to contain an array of associative arrays with the user names and ages, but instead, I get an behavior stating: `want to access property on non-object`. Iβve ensured that the array contains `User` objects, and Iβve also tried using `array_walk()` instead of `array_map()`, but I encountered the same scenario. Could this be related to how PHP handles destructuring in closures or is there another underlying scenario I'm missing? Any insights would be appreciated! I'm developing on Linux with Php. Is this even possible? What's the best practice here? This is happening in both development and production on Windows 11. Hoping someone can shed some light on this. Any ideas how to fix this?