How do you ensure that you don't get a "Call to a mem开发者_运维知识库ber function on a non object" fatal ?
Fox example, I often have something like this in my templates: (which I find very convenient and readable):
<?php echo $object->getRelatedObject()->getProperty()->formatProperty() ?>
However, this will work only if each method returns an object of correct class. But it is not always the case. Related object may not be present in the database, so it returns null and you are faced with a fatal error. Then you go and manually check the return values:
<?php if (is_object($object->getRelatedObject()) && is_object($object->getRelatedObject()->getProperty())):
<?php echo $object->getRelatedObject()->getPreperty()->formatProperty() ?>
<?php endif; ?>
But this isn't so readable anymore. How do you address this problem?
You can use method_exists
to make sure a specific method exist in an object or class.
Example:
method_exists($object->getRelatedObject(), 'getProperty');
You could also add an interface to the returned relatedObjects and/or property objects to make sure they do have the required methods. For the cases where the call would usually return NULL
, change it to a NullObject
that has this method.
It's also questionable if chaining from $object
all the way down to formatProperty
is a good idea. Your $object
requires intimate knowledge of the call graph there. You could consider hiding the delegate from the related object and move formatProperty
onto the relatedObject
to get and format in one go or allow getting the property with a formatting flag.
Each method can always throw an exception in the circumstance where it doesn't have an object to return. You then wrap your
echo $object->getRelatedObject()->getProperty()->formatProperty();
in a try/catch block
<?php
$relatedObject = $object->getRealtedObject();
if(is_object($relatedObject)){
$property = $relatedObject->getProperty();
if(is_object(property)){
....
}
}
<?php
$result="record not found";
if(is_object($object->getRelatedObject()) &&
is_object($object->getRelatedObject()->getProperty()))
{
$result=$object->getRelatedObject()->getPreperty()->formatProperty();
}
echo $result;
?>
thats a bit more readable :p
精彩评论