PHP Tip: Use Function Exists to avoid fatal errors

Have you encountered a FATAL ERROR in your blog when you tried to add a new function to your blog?

I did encounter this earlier when I was upgrading to wordpress 2.3. The reason for the fatal error is that I am calling a function that does not exist (perhaps the plugin that has that function has not been activated for example, similar_posts() won’t work unless the Similar Posts plugin is activated).

Solution:

There is a very simple solution to this problem so that you can avoid these kind of errors. You just have to make use of the function_exists function in PHP…

Continue with some code…
This is how it works.

<?php
if (function_exists(‘FUNCTION_CALL’))
{
FUNCTION_CALL();
}
?>

This code means that before you use the function FUNCTION_CALL, you have to make sure it exists. If that function does not exist, then nothing will happen however, if the function exists, then it will be called and executed.

Through this simple code, I have lessened the probability of getting Fatal errors due to undefined function calls.

8 thoughts on “PHP Tip: Use Function Exists to avoid fatal errors

  1. wow.. ur PHP skills are improving 😛

  2. Just the little guide I was looking for. Short and to the point 😉

    I prefer to use this method myself

    ...
    various php and html stuff
    ...

    just to give myself more leeway.
    Nevertheless, I didn’t know the exact format so your guide was exactly that.

    EDIT: Meh, no code allowed between code tags :-/
    Cheers!

    db0’s last blog post..Squashing Wodrpess Performance Bugs

  3. db0 – Oh, when I add this code usually, I turn off the visual editor. But sometimes, code tags are ok but the visual editor usually removes stuff especially the php codes 🙁

  4. Meh, I even tried to put the php code with a space between the < and ? but it was still eaten. Oh well 🙂

    db0’s last blog post..How to hunt for WordPress performance hogs

  5. @dB0 – LoL. Oh well, it’s because there’s not code tags in comments I guess?

  6. I found more information at on function checks at w3mentor.com/learn/php/php-language-basics/check-if-function-exists-in-php/

  7. Hi – one of those easy-to-get explanations – thanks.
    First it wouldn’t work, though, just copy/pasting your php code.
    It turned out that the single quotes

    came out wrong when pasting. Just retyping the ‘s makes it work.

  8. Always wondered what it was for… quite useful!

Leave a Reply