Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle "Call to a member function on a non object"

Tags:

php

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?

like image 650
Dziamid Avatar asked Jan 21 '23 22:01

Dziamid


1 Answers

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.

like image 197
Gordon Avatar answered Jan 29 '23 22:01

Gordon