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_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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With