Possible Duplicate:
Casting an Array with Numeric Keys as an Object
I was wondering about (object)
type casting.
It's possible to do a lot of useful things, like converting an associative array to an object, and some not so useful and a bit funny (IMHO) things, like converting a scalar value to object.
But how can I access the result of casting of an indexed array?
// Converting to object an indexed array
$obj = (object) array( 'apple', 'fruit' );
How about accessing a specific value?
print $obj[0]; // Fatal error & doesn't have and any sense
print $obj->scalar[0]; // Any sense
print $obj->0; // Syntax error
print $obj->${'0'}; // Fatal error: empty property.
print_r( get_object_vars( $obj ) ); // Returns Array()
print_r( $obj ); /* Returns
stdClass Object
(
[0] => apple
[1] => fruit
)
*/
The following works because stdClass
implements dynamically Countable
and ArrayAccess
:
foreach( $obj as $k => $v ) {
print $k . ' => ' . $v . PHP_EOL;
}
This is actually a reported bug.
It has been deemed as "too expensive to fix" and the resolution has been "updated the documentation to describe this useless quirk, so it is now officially correct behavior" [1].
However, there are some workarounds.
As get_object_vars
gives you nothing, only thing you can do is:
stdClass
using foreach
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"}
This is why you shouldn't cast non-associative array as object :)
But if you want to, do it in this way:
// 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 of
$obj = (Object) array('apple','fruit');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With