How 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:
- Using the is_callable function in PHP (Thursday, January 22nd 2009)
- Check if a class exists with PHP (Thursday, December 11th 2008)
- Get a list of all available constants with PHP (Thursday, July 17th 2008)
- Get a list of all available classes with PHP (Thursday, July 10th 2008)
- Get a list of all available functions with PHP (Thursday, July 3rd 2008)

Comments
blog comments powered by Disqus