在 PHP 中,我有时会使用 try/catch 捕获一些异常:
try {
...
} catch (Exception $e) {
// Nothing, this is normal
}
使用这种代码,我最终得到了一个变量 $e
,它是为一无所有(大量资源)而创建的,并且 PHP_MD(PHP Mess Detector)由于未使用的变量而创建了一个警告.
最佳答案
从 PHP 8 开始,可以使用非捕获捕获。
This is the relevant RFC ,以 48 票对 1 票获得赞成。
现在可以做这样的事情了:
try {
readFile($file);
} catch (FileDoesNotExist) {
echo "File does not exist";
} catch (UnauthorizedAccess) {
echo "User does not have the appropriate permissions to access the file";
log("User attempted to access $file");
}
这样,对于一些异常细节不相关且异常类型已经提供所有必要上下文的边缘情况,可以在不创建新变量的情况下捕获异常。
关于php - 有没有办法在不必创建变量的情况下捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4820211/