tags:

views:

191

answers:

2

I have a PHP object coming from an outside source (using PEAR's XML_Serializer). Some variables have dashes in the name like:

<?php
  $company->{'address-one'};

I just want to know what the best way to go through this object and rename the object properties with underscores replacing the dashes so I don't have to deal with the silly curlys and quotes.

+6  A: 

Loop through them all using get_object_vars() and replace as required:

function replaceDashes (&$obj) {
    $vars = get_object_vars($obj);
    foreach ($vars as $key => $val) {
        if (strpos($key, "-") !== false) {
            $newKey = str_replace("-", "_", $key);
            $obj->{$newKey} = $val;
            unset($obj->{$key});
        }
    }
}
nickf
+4  A: 

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.

nickf