Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?—i.e., Fatal error: Call to undefined function

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;

}
like image 651
supertrue Avatar asked Aug 19 '11 04:08

supertrue


People also ask

What is fatal error call to undefined function?

Fatal Error: 'Call to undefined function mysql_connect()' If you get an error like Fatal error: Call to undefined function mysql_connect() when trying to install GFI HelpDesk, it probably means that MySQL support has not been enabled for PHP on your server (that is, the PHP module php-mysql has not been installed).

What would occur if a fatal error was thrown in your PHP program?

It's an error that caused the script to abort and exit immediately. All statements after the fatal error are never executed. I strongly recommend you use an editor that will alert you to errors as you code. It will safe you a lot of time.

In which PHP version fatal errors become exceptions?

Fatal errors or recoverable fatal errors now throw instances of Error in PHP 7 or higher versions. Like any other exceptions, Error objects can be caught using a try/catch block.


1 Answers

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.

like image 156
AgentConundrum Avatar answered Oct 10 '22 23:10

AgentConundrum