implementing PHP 8.1 Closure Scopes and Inheritance in MySQLi Callbacks
I keep running into I'm working with an scenario with the scope of variables when using closures as callbacks in MySQLi functions in PHP 8.1... I have a class that manages database connections and queries, and I'm trying to use a closure to handle query results. However, the closure doesn't seem to have access to the class properties as expected. Here's a simplified version of my code: ```php class Database { private $connection; private $table = 'users'; public function __construct($host, $user, $password, $database) { $this->connection = new mysqli($host, $user, $password, $database); if ($this->connection->connect_error) { die('Connection failed: ' . $this->connection->connect_error); } } public function fetchUsers() { $query = "SELECT * FROM $this->table"; $result = $this->connection->query($query); $this->processResults($result); } private function processResults($result) { $callback = function($row) { echo "User ID: " . $row['id'] . " - Name: " . $row['name'] . '\n'; }; while ($row = $result->fetch_assoc()) { $callback($row); } } } $db = new Database('localhost', 'username', 'password', 'dbname'); $db->fetchUsers(); ``` When I run this code, I get an behavior stating that the array key 'id' is undefined when trying to access it in the closure, but if I print the `$row` variable before the callback call, it shows the expected data. It seems like the scope of `$row` isn't being maintained correctly. I've tried using the `use` statement to import the `$row` variable into the closure, but it still throws the same behavior. Is there a specific reason this is happening in PHP 8.1, or is there a better way to handle this scenario? Any help would be greatly appreciated! This issue appeared after updating to Php stable. This is for a REST API running on CentOS. Could someone point me to the right documentation?