为什么 is_null 在未设置的变量上抛出异常
Why is is_null throwing an exception on an unset variable
在 Laravel 终端命令的深处,我有以下代码:
<?php
/* ... */
class TrackShipment extends Command
{
/* ... */
public function handle()
{
/* ... */
if (is_null($eventHook) || $eventHook->uri != $statusHook->uri) {
/* ... */
}
}
}
当这部分代码执行时进程死掉,出现以下异常
ErrorException : Undefined variable: eventHook
这很令人惊讶,因为我在各种地方都使用了类似的代码,并且 PHP 将 return 在未设置的变量上调用 is_null 时为真,尽管它会抱怨它在 stderr 上有一个通知。
我假设 Laravel 正在从其代码中调整 PHP 设置以使 is_null 抛出异常而不是向 stderr 打印通知。这是什么设定?我将如何在 vanilla php7.2 中复制异常?
Laravel 最有可能使用 set_error_handler 来设置自定义错误处理函数:
https://www.php.net/manual/en/function.set-error-handler.php
您可以在其中定义管理错误的自定义方法。
对之前的回答感到抱歉。
函数is_null
在未定义变量时触发通知。 Laravel 将该通知转换为异常。
有两个函数可以用来检查不会触发通知的未定义变量。
isset
https://www.php.net/manual/en/function.isset.php
empty
https://www.php.net/manual/en/function.empty.php
第一个会 return false for null,所以你必须否定它。
在 Laravel 终端命令的深处,我有以下代码:
<?php
/* ... */
class TrackShipment extends Command
{
/* ... */
public function handle()
{
/* ... */
if (is_null($eventHook) || $eventHook->uri != $statusHook->uri) {
/* ... */
}
}
}
当这部分代码执行时进程死掉,出现以下异常
ErrorException : Undefined variable: eventHook
这很令人惊讶,因为我在各种地方都使用了类似的代码,并且 PHP 将 return 在未设置的变量上调用 is_null 时为真,尽管它会抱怨它在 stderr 上有一个通知。
我假设 Laravel 正在从其代码中调整 PHP 设置以使 is_null 抛出异常而不是向 stderr 打印通知。这是什么设定?我将如何在 vanilla php7.2 中复制异常?
Laravel 最有可能使用 set_error_handler 来设置自定义错误处理函数:
https://www.php.net/manual/en/function.set-error-handler.php
您可以在其中定义管理错误的自定义方法。
对之前的回答感到抱歉。
函数is_null
在未定义变量时触发通知。 Laravel 将该通知转换为异常。
有两个函数可以用来检查不会触发通知的未定义变量。
isset
https://www.php.net/manual/en/function.isset.phpempty
https://www.php.net/manual/en/function.empty.php
第一个会 return false for null,所以你必须否定它。