bottomrocks bottomrocks - 2 months ago 8
PHP Question

PHP Fatal error: Call to a member function getId() on null - its supposed to be null (sometimes), how to handle correctly?

Sometimes the expected result should be null, other times it's not (if it's not null, I want code function x to parse. If not null, code y parses).. not sure how to handle this appropriately:

$myID = is_object($widget->getParent()->getId()) ? $widget->getParent()->getId() : '';

if (isset($myID)){
//....code here


Result:

PHP Fatal error: Call to a member function getId() on null in \htdocs\program\widget\Controller\WidgetController.php on line 212


Line 212:

$myID = is_object($widget->getParent()->getId()) ? $widget->getParent()->getId() : '';


I've also tried variations of:
is_object()

is_array()

null ==

null !==


None seem to allow the code to process as expected.

Answer

Sounds like $widget->getParent() is returning null maybe store that and check it first? I'd guess that getParent() might return null on a root element.

$myParent = widget->getParent();
if($myParent){
  $myID = is_object($myParent->getId()) ? $myParent->getId() : '';
  if (isset($myID)){
       //....code here
  }
} else {
  // Error handling
}