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;
}