This actually reported an error .
This is considered "too costly to fix," and the documentation was "updated to describe this useless quirk, so now it's officially the correct behavior" [1] .
However, there are workarounds .
Since get_object_vars gives nothing, only you can do the following:
- You can iterate over
stdClass using foreach - You can drop it as an array.
- You can change it to an object using json_decode + json_encode (this is a dirty trick)
Example 1 .:
$obj = (object) array( 'apple', 'fruit' ); foreach($obj as $key => $value) { ...
Example 2 .:
$obj = (object) array( 'apple', 'fruit' ); $array = (array) $obj; echo $array[0];
Example 3 .:
$obj = (object) array( 'apple', 'fruit' ); $obj = json_decode(json_encode($obj)); echo $obj->{'0'}; var_dump(get_object_vars($obj)); // array(2) {[0]=>string(5) "apple"[1]=>string(5)"fruit"}
That is why you should not use a non-associative array as an object :)
But if you want, do it like this:
// PHP 5.3.0 and higher $obj = json_decode(json_encode(array('apple', 'fruit'), JSON_FORCE_OBJECT)); // PHP 5 >= 5.2.0 $obj = json_decode(json_encode((Object) array('apple', 'fruit')));
instead
$obj = (Object) array('apple','fruit');
Peter
source share