简体   繁体   English

是否可以在 PHP 中防止“致命错误:调用未定义的函数”?

[英]Is it possible in PHP to prevent “Fatal error: Call to undefined function”?

In PHP, is there any way that I can ignore functions that are undefined instead of throwing a fatal error that is visible in the browser?—ie, Fatal error: Call to undefined function在 PHP 中,有什么方法可以忽略未定义的函数而不是抛出在浏览器中可见的致命错误?-即致命错误:调用未定义的函数

I know that there is the practice of wrapping all custom functions in a conditional as below, but is there a programmatic way to get this effect?我知道有一种将所有自定义函数包装在如下条件中的做法,但是有没有一种编程方式来获得这种效果?

if (function_exists('my_function')) { 

   // use my_function() here;

}

No. Fatal errors are fatal.不。致命错误是致命的。 Even if you were to write your own error handler or use the @ error suppression operator, E_FATAL errors will still cause the script to halt execution.即使您要编写自己的错误处理程序或使用@错误抑制运算符, E_FATAL错误仍会导致脚本停止执行。

The only way to handle this is to usefunction_exists() (and possibly is_callable() for good measure) as in your example above.处理这个问题的唯一方法是使用function_exists() (并且可能是is_callable()以进行良好的衡量),如上面的示例所示。

It's always a better idea to code defensively around a potential (probable?) error than it is to just let the error happen and deal with it later anyway.围绕潜在的(可能的?)错误进行防御性编码总是比让错误发生并稍后处理它更好的主意。

EDIT - php7 has changed this behavior, and undefined functions/methods are catchable exceptions.编辑- php7 改变了这种行为,未定义的函数/方法是可捕获的异常。

In php 7, this is now possible.在 php 7 中,这现在是可能的。

Example codez:示例代码:

try {
    some_undefined_function_or_method();
} catch (\Error $ex) { // Error is the base class for all internal PHP error exceptions.
    var_dump($ex);
}

demo演示

http://php.net/manual/en/migration70.incompatible.php http://php.net/manual/en/migration70.incompatible.php

Many fatal and recoverable fatal errors have been converted to exceptions in PHP 7. These error exceptions inherit from the Error class, which itself implements the Throwable interface (the new base interface all exceptions inherit).许多致命和可恢复的致命错误已在 PHP 7 中转换为异常。这些错误异常继承自 Error 类,该类本身实现了 Throwable 接口(所有异常继承的新基接口)。

What you are asking for seems a little goofy, but you can get a similar effect by declaring all your functions as methods of a class and then implement __call as a method of that class to handle any undefined method calls.您所要求的似乎有点愚蠢,但是您可以通过将所有函数声明为类的方法,然后将__call实现为该类的方法来处理任何未定义的方法调用来获得类似的效果。 You can then handle calls to undefined methods however you like.然后,您可以根据自己的喜好处理对未定义方法的调用。 Check out the documentation here .此处查看文档。

If you would like to suppress this error while working with objects use this function:如果您想在处理对象时抑制此错误,请使用此函数:

function OM($object, $method_to_run, $param){ //Object method
    if(method_exists(get_class($object), $method_to_run)){
        $object->$method_to_run($param);
    }        
}

Regards问候

we can hide errors but this will log in apache error log我们可以隐藏错误,但这会登录 apache 错误日志

//Set display error true. //设置显示错误为真。

ini_set('display_errors', "0");

//Report all error except notice //报告除通知外的所有错误

ini_set('error_reporting', E_ALL ^ E_NOTICE ^ E_STRICT);

//We can use try catch method //我们可以使用try catch方法

try {
    my_method();
} catch (\Error $ex) { // Error is the base class for all internal PHP error exceptions.
    var_dump($ex);
}

//Check method existance //检查方法是否存在

function_exists() function_exists()

Prevent no.防止没有。 But catch and log yes, using register_shutdown_function()但是捕获并记录是的,使用 register_shutdown_function()

See PHP manual参见PHP 手册

function shutDown_handler()
{
   $last_error = error_get_last();
   //verify if shutwown is caused by an error
   if (isset ($last_error['type']) && $last_error['type'] == E_ERROR)
   {
      /*
        my activity for log or messaging
        you can use info: 
          $last_error['type'], $last_error['message'],
          $last_error['file'], $last_error['line']
          see about on the manual PHP at error_get_last()
      */
   }
}

register_shutdown_function ('shutDown_handler');

I found in PHP 7 that try/catch works for the "Call to undefined function" error.我在 PHP 7 中发现 try/catch 适用于“调用未定义函数”错误。 The Exception object that is caught is not of class Throwable and not ErrorException but Error.被捕获的异常对象不是 Throwable 类,也不是 ErrorException 而是 Error。

The exception object received by catch contains the error message, the file and line nr, and stack trace, but does not contain the severity code. catch 接收到的异常对象包含错误信息、文件和行号、堆栈跟踪,但不包含严重性代码。

This catch allows the program to do its own logging or analysis, and hides the error message from the user-visible output (but will log the error in the PHP error log), just what is wanted on production websites.此捕获允许程序进行自己的日志记录或分析,并从用户可见的输出中隐藏错误消息(但会将错误记录在 PHP 错误日志中),这正是生产网站上需要的。 It also allows execution to continue, which can be dangerous, but you can simply place "exit;"它还允许继续执行,这可能很危险,但您可以简单地放置“退出”; at the end of the catch code block to prevent the program from continuing.在 catch 代码块的末尾,以防止程序继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM