How do you ensure that you don’t get a “Call to a member 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_existsto make sure a specific method exist in an object or class.Example:
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 aNullObjectthat has this method.It’s also questionable if chaining from
$objectall the way down toformatPropertyis a good idea. Your$objectrequires intimate knowledge of the call graph there. You could consider hiding the delegate from the related object and moveformatPropertyonto therelatedObjectto get and format in one go or allow getting the property with a formatting flag.