PHP: replacing hyphens in object variables with underscores

I have a PHP object coming from an external source (using PEAR XML_Serializer). Some variables have a dash in the type name:

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

I just want to know how best to go through this object and rename the properties of the object with underscores replacing the dash, so I don't have to deal with silly shapes and quotes.

+3
source share
2 answers

Scroll them all using get_object_vars()and replace them as needed:

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});
        }
    }
}
+7
source

I just thought of something else:

PHP5 __get __set, , , . , , , , :

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"

, . , , , PHP Reflection -.

+6

Source: https://habr.com/ru/post/1717889/


All Articles