2

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

rogy
  • 440
  • 6
  • 23
  • 1
    Not 100% sure what you mean however to check if it is an object use `is_object` http://php.net/manual/en/function.is-object.php – Ian Jul 16 '14 at 16:03
  • Yes that is what I meant! sorry if I was unclear – rogy Jul 16 '14 at 16:19

2 Answers2

3

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.

arielnmz
  • 8,354
  • 9
  • 38
  • 66
0

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.

  • 2
    Just for the record: I like this idea, but the `try` block doesn't catch *warnings* nor *notices*, only *exceptions*, so this won't work. You'll need a [custom error handler](http://stackoverflow.com/questions/1241728/can-i-try-catch-a-warning) in this case. You can try this example here: [sandbox.onlinephpfunctions.com](http://sandbox.onlinephpfunctions.com/code/04d60bfd2ebbc6a1c6993ef8619954ccbb70ba15). – arielnmz Jul 16 '14 at 19:57