【问题标题】:Why is is_null throwing an exception on an unset variable为什么 is_null 在未设置的变量上抛出异常
【发布时间】:2020-02-24 12:40:43
【问题描述】:

在 Laravel 终端命令的深处,我有以下代码:


<?php
/* ... */

class TrackShipment extends Command
{

   /* ... */

    public function handle()
    {
      /* ... */
         if (is_null($eventHook) || $eventHook->uri != $statusHook->uri) {
          /* ... */
         }
     }
}

当这部分代码执行时,进程终止并出现以下异常

ErrorException  : Undefined variable: eventHook

这很令人惊讶,因为我在各种地方都使用了类似的代码,当对未设置的变量调用 is_null 时 PHP 将返回 true,尽管它会在 stderr 上抱怨它并发出通知。

我假设 Laravel 正在从其代码中调整 PHP 设置,以使 is_null 抛出异常,而不是向 stderr 打印通知。这是什么设置?我将如何在香草 php7.2 中复制异常?

【问题讨论】:

  • 不确定stackoverflow.com/questions/16537562/… 是否仍然有效或是否已过时。
  • NULL 和未定义的变量不同,对我来说出现这种错误很正常。您必须在您的条件中添加isset($eventHook) and ...。异常是正常的。我想这取决于你的error_reporting 级别
  • 尝试使用empty()

标签: php laravel command-line-interface php-7


【解决方案1】:

Laravel 最有可能使用 set_error_handler 来设置自定义错误处理函数:

https://www.php.net/manual/en/function.set-error-handler.php

您可以在其中定义管理错误的自定义方式。

这里是:https://github.com/laravel/framework/blob/a05b9dcb3b1e8069b59a9af90d0b157c30382131/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php#L43

抱歉之前的回答。

【讨论】:

    【解决方案2】:

    如果未定义变量,函数is_null 会触发通知。 Laravel 将该通知转换为异常。

    有两个函数可以用来检查不会触发通知的未定义变量。

    1. issethttps://www.php.net/manual/en/function.isset.php
    2. emptyhttps://www.php.net/manual/en/function.empty.php

    第一个会为null返回false,所以你必须否定它。

    【讨论】:

      猜你喜欢
      • 2021-05-07
      • 2022-09-30
      • 2013-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-12
      • 2010-12-09
      • 1970-01-01
      相关资源
      最近更新 更多