【问题标题】:PHP - Skip object of class nullPHP - 跳过类 null 的对象
【发布时间】:2019-12-19 22:24:48
【问题描述】:

我正在从我的数据库中提取特定实体的数据,并形成与它们相关的其他表。

当 db 中的某个对象为空时,如何跳过错误?

错误是:

在 null 时调用成员函数 getName()

代码:

$results = $this->getMyRepository()->findAll();

    $rows = [];

    $rows[] = array(
        "id",
        "user",
        "category"
    );

    foreach ($results as $row) {
        $rows[] = [
            $row->getId(),
            $row->getUser()->getFullName(),
            $row->getCategory()->getName(),
        ];
    }
    return $rows;
}

【问题讨论】:

    标签: php arrays class symfony-3.4


    【解决方案1】:

    在使用它之前,您可以简单地检查变量是否为空

     foreach ($results as $row) {
          $rows[] = [
            $row->getId(),
            $row->getUser()->getFullName(),
            !is_null($row->getCategory()->getName()) ? $row->getCategory()->getName() : '',
          ];
       }
    

    文档:is_null

    【讨论】:

    • 如果getCategory 给你null,这不会跳过异常。这仍然会在其上调用getName。这可以工作,但 is_null 应该检查类别,而不是名称 - !is_null($row->getCategory()) ? $row->getCategory()->getName() : ''
    • 如何传递$row->getCreated(new \DateTime())->format('Y-m-d'),因为“format”不能在null上调用? @Haru
    • 再次,三元运算符或空排序规则。例如($row->getCreated() ?? new \DateTime())->format('Y-m-d')
    • 向我们展示您到底在做什么。你得到什么错误?
    • 请确保正确放置括号。它有效,请参阅这个 sn-p - sandbox.onlinephpfunctions.com/code/…
    【解决方案2】:

    这不是错误,而是异常。 “@”运算符错误might be suppressed

    你不能只是跳过异常。要处理它们,您需要使用 try-catch 块。

    也许您想检查用户和类别是否存在。您的代码可能如下所示(使用三元运算符)。

    foreach ($results as $row) {
        $rows[] = [
            $row->getId(),
            ($user = $row->getUser()) ? $user->getFullName() : null,
            ($category = $row->getCategory()) ? $category->getName() : null,
        ];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 2022-11-29
      • 2012-03-22
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多