Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Replace Dashes in Object Variables With Underscores

Tags:

object

php

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.

like image 255
dprevite Avatar asked Jun 05 '26 21:06

dprevite


1 Answers

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.

like image 199
nickf Avatar answered Jun 07 '26 10:06

nickf