1

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?

3
  • You can use getProperty($o->wife, 'name', 'No Name') with your existing code but you will have to assert that $o->wife exists. Commented Apr 4, 2016 at 3:57
  • That's exactly the issue. Every level on the way down could or could not exist. That's why I want this check. Commented Apr 4, 2016 at 4:47
  • try below solution.. Commented Apr 4, 2016 at 5:00

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

That's very clever. Resetting $object to be the next one down the line. It works exactly as intended, goes arbitrarily deep and could even be simply adjusted to account for assoc arrays instead of objects as well. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.