PHP”;未找到异常”;


PHP "Exception not found"

我遇到了一个有趣的问题。当我试图理解为什么某个网站向浏览器返回http代码500时,我发现了

PHP Fatal error:  Class 'MZ''MailChimpBundle''Services''Exception' not found in /var/www/website/vendor/bundles/MZ/MailChimpBundle/Services/MailChimp.php on line 41

在apache日志中。看看上面提到的行:

throw new Exception('This bundle needs the cURL PHP extension.');

我现在明白了如何让网站正常工作,但我仍然想知道为什么抛出异常的代码(这会导致更有用的日志消息)失败。原因可能是什么?

MZMailChimpBundle在MZ'MailChimpBundle'Services命名空间中不包含名为Exception的类。

由于这个简单的事实,并且异常应该发出的错误消息与集成问题有关(检查curl库),我认为这是一个错误。

原来的意思是'Exception,而不是Exception。这是命名空间中可能发生的一个常见错误。要修复文件,请将'Exception别名/导入为Exception:

namespace MZ'MailChimpBundle'Services;
use Exception;

和/或更改MZMailChimpBundle/Services/MailChimp.php:中的new

throw new 'Exception('This bundle needs the cURL PHP extension.');

请参阅相关问题:如何使用php的"根"命名空间?和具有相同类"Namespace''Example"的方法未找到错误消息:从PHP中另一个命名空间中的类调用静态方法。

扩展@hakre答案,您可以使用简化其使用

use 'Exception as Exception;

这样,您就可以在不记住反斜杠的情况下抛出异常,如:

throw new Exception('This bundle needs the cURL PHP extension.');

在我看来,这行试图在当前命名空间中抛出用户定义的Exception,而不是PHP本身的内置Exception类