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

老子叫甜甜 提交于 2019-11-27 15:05:39
AgentConundrum

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.

The only way to handle this is to use function_exists() (and possibly is_callable() for good measure) as in your example above.

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.

In php 7, this is now possible.

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

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).

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. 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

//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 {
    my_method();
} catch (\Error $ex) { // Error is the base class for all internal PHP error exceptions.
    var_dump($ex);
}

//Check method existance

function_exists()

Prevent no. But catch and log yes, using register_shutdown_function()

See PHP manual

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');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!