PHP:捕获 fatal error (调用非对象的成员函数)

标签 php error-handling

有时,我的脚本无法读取服务器的输出并发生以下错误:

PHP fatal error :调用非对象上的成员函数 somefun()

这不是我无法解决的问题,但这会导致我的脚本崩溃。有没有一种方法可以创建一个在发生此特定错误时运行的函数?我认为进行 try-catch 或类似操作是不切实际的,因为我必须找到调用成员函数的每个实例并测试该对象是否存在(数千个)。

最佳答案

在 PHP 7 中

是的,捕获一个“错误”throwable,见http://php.net/manual/en/language.errors.php7.php

演示:https://3v4l.org/Be26l

<?php

$x = "not an object";

try {
 $x->foo();
} catch (\Throwable $t) {
 echo "caught";
}

在 PHP 5 中

Is there a way I can create a function that gets run when this particular error occurs?

是的,您可以使用“register_shutdown_function”让 PHP 在遇到此错误后死前调用一个函数。

PHP: catching a fatal error (call to member function on a non-object)

如果这就是“捕获”的意思,则无法从此错误中恢复,因为 PHP 已将“调用非对象上的成员函数”定义为“致命”错误。参见 PHP turn "Call to a member function on a non-object" into exception讨论为什么会这样。

关于PHP:捕获 fatal error (调用非对象的成员函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11489255/

相关文章:

php - 如何使用__dir__?

php - 在提交表单时使用 jquery 发送发布数据

php - Thrift能否在php中维护Memcached持久连接

php - MySQL PHPExcel 查询执行时间太长

Php邮件从上一页拉取表单数据

C++:关于运行时警告错误和消息的最佳实践是什么?

c++ - 使用>>链检查非整数输入(C++)

.net - 如何针对未处理的异常进行编码

powershell - 从Get-ADObject服务器超时捕获错误

perl - 使用perl评估归档的解码文件