Casting Weirdness With PHP

When my coworker today asked if he could cast an array to a object. I couldn’t really answer the question. Don’t think i ever done that. So let’s try. right?

Cast array to object
$arr = array('foo' => 'baz');
$obj = (object) $arr;

var_dump($obj);
object(stdClass)#1 (1) {
  ["foo"]=>
  string(3) "baz"
}

Ha that’s cool. It actually works. But wait. What happens when we use a numeric index?

Cast array to object
$arr = array(0 => 'bar', 'foo' => 'baz');
$obj = (object) $arr;

var_dump($obj);
object(stdClass)#1 (2) {
  [0]=>
  string(3) "bar"
  ["foo"]=>
  string(3) "baz"
}

WTF? We just created $obj->0 which should not be allowed in PHP as far as i know. So let’s make sure i am not mistaking.

Assign value to numeric class property
$foo = new stdClass();
$foo->0 = 'bar';

PHP Parse error: syntax error, unexpected ‘0’ (T_LNUMBER), expecting identifier (T_STRING) or variable (T_VARIABLE) or ‘{’ or ‘$’ in foo.php on line 5

But casting the array didn’t complain about a thing. Can we access this property? Well! Not calling it directly. At least not that i know of. But looping over the object’s properties does seem to work.

Loop object properties
// Parse error
// var_dump($obj->0);

foreach ($obj as $key => $val) {
  var_dump($key);
  var_dump($obj->$key);
}
int(0)
PHP Notice:  Undefined property: stdClass::$0 in foo.php on line 14
NULL
string(3) "foo"
string(3) "baz"

It’s not that i was planning on ever using this. Or advising other people to use it. In the contrary. But i guess it’s not completely useless. But care is required when doing so.

comments powered by Disqus