How to check if a function exists in PHPHow to check if a function exists in PHP

Posted January 9th, 2009 in PHP

You can test if a function exists in PHP with the function_exists() function, which returns true if the function exists and false if it does not. You can then take appropriate action to include the necessary library files or create the function etc.

If we have the following function:

function foo() {
    ...
}

Then calling:

function_exists('foo')

would return true.

If we did not have a function declared called "bar" then calling:

function_exists('bar')

would return false.

Putting this together, we could test to see if the function "bar" exists, and if not, create it like so:

if(!function_exists('bar')) {

    function bar() {
        ...
    }

}

Alternatively you could include a file (or do some other action):

if(!function_exists('bar')) {
    include('bar.php');
}

If you want to test if a method of a class exists use the method_exists() function instead. The method_exists() function will be covered this time next week.

Related posts:

Comments

blog comments powered by Disqus