rogy
rogy

Reputation: 450

Safest method to catch 'call to a member function on a non-object'

Inherited a piece of code where an update to a plugin has started causing this error

Fatal error: Call to a member function getId() on a non-object in...

Where the line in question is $shippingId = $order->getShippingAddress()->getId();

The update to the surrounding code, means that this function returning nothing is fine and the rest of the code can function with $shippingId not existing

What I need is a method of saying

if ($shippingId = $order->getShippingAddress()->getId() WORKS)
  do_these_things()

and then instead of error'ing just carries on if not

Upvotes: 2

Views: 2014

Answers (2)

You can use the method mentioned by arielnmz or you could use custom exception handler.

try{
if ($shippingId = $order->getShippingAddress()->getId() WORKS)
   do_these_things();
}
catch(Exception e){
//Echo out the error msg or save it on your error log stash. up to you
   $error_msg=$e->getMessage();
}
//your regular codes

Using this way, if there is an error within the try block, the error is caught on the catch block and your code will carry on the normal execution pattern.

Upvotes: 0

arielnmz
arielnmz

Reputation: 9115

I would do this:

if (isset($order->getShippingAddress()) && is_object($order->getShippingAddress()) ) {
    /* It is an object and it isn't null */
} else {
    /* It doesn't */
}

isset() checks if the expression is not null and has a value (to avoid null-pointing) and is_object() checks wether such expression is an object.

Upvotes: 3

Related Questions