PHP: Check if function exists.

This is a short guide on how to check to see if a PHP function exists (i.e. if it has been defined or not).

I think it is fair to say that we have all seen this error at some stage or another:

Fatal error: Call to undefined function my_function_name()

In most cases, the error can be fixed by making sure that the function exists or that a typo in the name isn’t the cause. However, in some use cases, you may not know for sure if a given function exists. For example: On many PHP installations, the curl functions are not enabled by default. This means that attempting to use curl may result in:

Fatal error: Call to undefined function curl_init()

Now, you might say that the curl functions should be enabled. However, what if you are writing portable code and you want to be able use a fallback method if the curl functions are not enabled?

This is where the function function_exists comes to the rescue:


//Check to see if the function curl_init is defined.
    //It is defined, so we can use it.
} else{
    //The function does not exist.
    //Use fallback.

In the code above, we used function_exists to to check whether the function curl_init exists. If it exists, we assume that the curl extension is installed and that we can use the curl functions. However, if function_exists returns a false value, then we know that the function is not defined and that we need to use a fallback / alternative method.