I just thought of another way:
Using PHP5's magic methods __get
and __set
you could make it look like the underscored properties exist, when they actually don't. The benefit in this is that if there's some other code which doesn't expect the field names to be transformed, they'll still work:
function __get($var) {
if (strpos($var, '-') !== false) {
$underscored = str_replace("-", "_", $var);
return $this->$underscored;
}
}
function __set($var, $val) {
if (strpos($var, '-') !== false) {
$underscored = str_replace("-", "_", $var);
$this->$underscored = $val;
}
}
echo $company->{'address-one'}; // "3 Sesame St"
echo $company->address_one; // "3 Sesame St"
// works as expected if you somehow have both dashed and underscored var names
// pretend: $company->{'my-var'} ==> "dashed", $company->my_var ==> "underscored"
echo $company->{'my-var'}; // "dashed"
echo $company->my_var; // "underscored"
Of course, you have to find some way to actually attach these methods to the class of your elements. I'm not very good with this sort of thing, but perhaps it would work by using PHP's Reflection functions, or by creating a wrapper class.