I'm having some trouble using PHP object property names in a flexible way, similar to array keys.
My understanding is that an array key can be any string or integer, e.g
$arr = array("crash-me" => "value");
is a valid key/value pair.
Now if I "cast" that to an object:
$obj = (object) $arr;
have I done something illegal, because of the dash in the key string?
A simple example shows my dilema:
<?php
error_reporting(-1);
$obj = new stdClass;
$prop = "crash-me";
$arr = array();
$obj->$prop = "no crash";
$obj->$prop = $arr; // bp here and $obj->$prop is correct
print_r($obj); // bp here, inspect $obj->$prop and... xdebug/php will crash.
exit;
This will crash eclipse-pdt using xdebug when you inspect the value of the $obj before the print_r().
However, without bp, contents are printed correctly from print_r() at exit.
stdClass Object ( [crash-me] => Array ( ) )
Note that if I stuff something into the array when assigning it to the property, things are OK:
$obj = new stdClass;
$prop = "crash-me";
$arr = array("works_ok");
$obj->$prop = "no crash";
$obj->$prop = $arr;
print_r($obj);
exit;
Bottom-line, I'd like to use property names with dashes and possibly other punctuation similar to array key. Is it possible? Or am I doing something illegal by assigning an empty array, in which case wouldn't an error be caught?
Thanks ahead for your kind consideration!
on edit, I forgot another part of puzzle - the code below does not crash. In this case, the property name does not have a dash, however, the array key is empty!
$obj = new stdClass;
$prop = "crash_me"; // note underscore
$arr = array();
$obj->$prop = "no crash";
$obj->$prop = $arr; // bp here and $obj->$prop is correct
print_r($obj); // bp here, inspect $obj->$prop and... no crash!
exit;
Sorry for the confusion! It's probably something obvious I am missing.
On second edit-
To clarify, I was hoping to read property names from json_decode() and simply use the objects without having to convert to arrays. It was an experiment with dynamic code generation using keys from json data files. Per discussion below, looks like if I want to continue with PHP for this, I'll need the $arr['key1']['key2']... syntax and have the decoder use the "array" flag.
Thanks for the great replies!