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

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

有时预期结果应该为空,有时则不是(如果它不为空,我希望代码函数 x 解析。如果不为空,代码 y 解析)。不知道如何适当地处理这个:

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

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

结果:

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

第 212 行:

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

我也尝试过以下变体: is_object() is_array() null == null !==

None 似乎允许代码按预期处理。

听起来 $widget->getParent() 是 returning null 也许存储它并先检查它?我猜 getParent() 可能 return 在根元素上为 null。

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