我以正确的方式使用 getCreatedTime() 吗?

Am I using getCreatedTime() the right way?

这是我的代码:

$node = Drupal::request()->attributes->get('node');
$created_time = $node->getCreatedTime();

Drush 看门狗显示以下错误:

Error: Call to a member function getCreatedTime() on null in Drupal...

有什么问题?

最好这样获取当前节点:

$node = \Drupal::routeMatch()->getParameter('node');

但它并不总是return节点对象。例如,如果您在视图页面上,它将 returns 为空。因此,您必须检查 returned 值:

if ($node instanceof \Drupal\node\NodeInterface) {
  $created_time = $node->getCreatedTime();
}