17

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;

}
3
  • 5
    I would be interested to know what you are trying to achieve. What could possibly work correctly when skipping functions? Aug 19, 2011 at 4:47
  • 1
    To @PhilWallach's comment: "not all functions are created equal". It entirely depends on the application domain. Some can just do optional things, like a non-critical refining of some variable. Catching/skipping undef. functions are every bit as legit as doing the very same thing with methods. There should just be a global __call magic method. (Note: "when should OOP be used instead" is an entirely different question, orthogonal to the point here.)
    – Sz.
    Sep 28, 2018 at 12:12
  • //What could possibly work correctly when skipping functions?// This is a well-known element of metaprogramming in mainstream programming languages ... See for example: method-missing
    – dreftymac
    Oct 4, 2019 at 21:57

7 Answers 7

37

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.

5
  • See stackoverflow.com/questions/277224/… for possible workarounds
    – ncatnow
    Jul 6, 2013 at 5:30
  • 1
    @ncatnow I know about register_shutdown_function() but didn't include it in my answer because it didn't seem to relate to the question at hand. That function doesn't make fatal errors not fatal, it just lets the application scream in agony before it dies. Jul 7, 2013 at 6:43
  • Sure thing @AgentConundrum - I added the link as I felt it did provide a workaround to the question, specifically "instead of throwing a fatal error that is visible in the browser", register_shutdown_function() would allow the developer to take alternative action on a fatal error.
    – ncatnow
    Jul 8, 2013 at 8:53
  • Those looking for class methods, see method_exists. Aug 15, 2015 at 21:02
  • @AgentConundrum Just to add about PHP 7. I was trying to catch the error using ParseError and Exception, but none did it. But... using Throwable does the job! Thanks for the inspiration you gave me. Feb 23, 2017 at 6:14
25

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

1
2

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.

1

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

2
  • The only down side is that you have to use option array for method parameters. Which means that the method/object have to be design in certain pattern. (works with magic methods like __set().
    – DevWL
    Sep 21, 2014 at 1:04
  • Some years back I started using this same strategy, but I abandoned it because it interferes with most IDE's ability to do static analysis. Being able to have an IDE tell me all the places in my code base which call certain method is very valuable, and when doing dynamic method calls (like this sample does), they can no longer provide that functionality, nor many other useful static analysis features.
    – goat
    Mar 6, 2020 at 19:56
0

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

1
  • The question asks if there is a way of automatically implementing conditional logic, simply hiding fatal errors does not achieve this, and imo should be avoided in all cases.
    – Edward
    Aug 29, 2017 at 11:36
0

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');
0

I found in PHP 7 that try/catch works for the "Call to undefined function" error. The Exception object that is caught is not of class Throwable and not ErrorException but 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.

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

2
  • The Exception object that is caught is not of class Throwable and not ErrorException but Error. It throws an "Error" exception that is a subclass of Throwable according with PHP7's manual. So it is NOT an Error like we are used to, with an Error Level or Severity, it is not that kind of error like for example a Fatal Error or the ones in PHP Error Levels.
    – Esteban
    Jan 1, 2022 at 16:11
  • This catch allows .... (but will log the error in the PHP error log), ... Not true, open your php_error.log, throw and catch an Error Exception in the try/catch, and no lines are added in the log.
    – Esteban
    Jan 1, 2022 at 16:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.