Coo
Coo

Reputation: 1882

PHP accessing deeper object properties through string variable

I have this simple function to not get any warnings when a property doesn't exist:

function getProperty($object, $property, $default = ""){
    if (is_object($object) && isset($object->$property)) return $object->$property;

    return $default;
}

That works great for something like this:

$o = new stdClass();
$o->name = "Peter";

$name = getProperty($o, 'name', 'No name');
$email = getProperty($o, 'email', 'No email');

That will return $name = 'Peter' and $email = 'No email'.

Now I want to do the same for the following object:

$o = new stdClass();
$o->wife = new stdClass();
$o->wife->name = "Olga";

getProperty($o, "wife->name", "No name");

This doesn't work as the function will now try to get the property literally named "wife->name" which doesn't exist.

Is there a way I can adjust this function so it can go arbitrarily deep into an object?

Upvotes: 1

Views: 297

Answers (1)

Chetan Ameta
Chetan Ameta

Reputation: 7896

You can explode argument by -> and iterate it. try below solution:

function getProperty($object, $property, $default = ""){

    $properties = explode('->', $property);

    if($properties){
        foreach($properties as $val){
            if(isset($object->$val)){
                $object = $object->$val;
            } else{
                break;
            }
        }
    }

    if (!is_object($object) && $object) return $object;

    return $default;
}

$o = new stdClass();
$o->name = "Peter";

echo $name = getProperty($o, 'name', 'No name'); //output: Peter
echo $email = getProperty($o, 'email', 'No email'); //output: No email

$o = new stdClass();
$o->wife = new stdClass();
$o->wife->name = "Olga";

echo getProperty($o, "wife->name", "No name"); //output: Olga

Upvotes: 1

Related Questions