Description
Description
The following code fetches a object with a single property whose name and value is '42'.
<?php
$dbh = new mysqli('localhost', 'richard');
$res = $dbh->query('SELECT 42');
$obj = $res->fetch_object();
$prop = 42;
var_dump($obj);
echo ">{$obj->$prop}<\n";
$obj = json_decode(json_encode($obj));
var_dump($obj);
echo ">{$obj->$prop}<\n";
This results in this output:
object(stdClass)#3 (1) {
[42]=>
string(2) "42"
}
PHP Notice: Undefined property: stdClass::$42 in /home/richard/test.php on line 8
><
object(stdClass)#4 (1) {
["42"]=>
string(2) "42"
}
>42<
The first var_dump
confirms that $obj
does contain the expected property. However it is not possible to access it via the $obj->$prop
syntax, nor with $obj->{42}
or $obj->{'42'}
. Transforming it to JSON and back turns it into a more regular object which can be accessed with either of these syntaxes.
I expected the ><
in the output to read >42<
. Changing $res->fetch_object()
to (object)$res->fetch_assoc()
has the expected effect, and provides an adequate work-around.
My guess is that this is another instance of this bug/oddity that was fixed in PHP 7.2 that escaped being fixed then.
Just in case its relevant, I'm testing with MariaDB 10.5.12.
PHP Version
PHP 8.1.2 (also 8.0.15 and 7.4.27)
Operating System
Debian 11