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?
getProperty($o->wife, 'name', 'No Name')with your existing code but you will have to assert that$o->wifeexists.