What is PHP function_exists() Function?
If you want to know whether a function is available to use which means if the function already defined use PHP function_exists() function – it could be a built-in (internal) function or a user-defined function.
Syntax:
function_exists(function_name)
Parameters:
The function has one parameter which is required-
function_name (Required): It is mentioned as a function. The name of the function, be it a user-defined function or built-in function.
Return Values:
The function returns –
- TRUE: If the mentioned function exists.
- FALSE: If the mentioned function doesn’t exist.
Examples:
Example 1:
<?php
if(function_exists("strlen")){ echo "Function exists";}
else{ echo "Function doesn't exists";}
?>
Output:
Function exists
Explanation:
The built-in function strlen() exists, so the function function_exists() returns TRUE and the script prints “Function exists”.
Example 2:
<?php
function my_function(){}
if(function_exists("my_function")){ echo "Function exists";}
else{ echo "Function doesn't exists";}
echo "<br />";
if(function_exists("your_function")){ echo "Function exists";}
else{ echo "Function doesn't exists";}
?>
Output:
Function exists
Function doesn’t exists
Explanation:
As the user-defined function my_function() is defined in line 2, the function function_exists() returns TRUE and the script prints “Function exists” in line 3.
There is no function named your_function() as user-defined function or built-in function, the function function_exists() returns FALSE (line 6) and the script prints “Function doesn’t exist” in line 7.
Example 3:
<?php
if(function_exists("strlen")){ echo "Function exists";}
else{ echo "Function doesn't exists";}
echo "<br />";
echo strlen("PHP Function function_exists");
?>
Output:
Function doesn’t exist
Fatal error: Uncaught Error: Call to undefined function strlen() in D:\xampp\htdocs\function_exists.php:5 Stack trace: #0 {main} thrown in D:\xampp\htdocs\function_exists.php on line 5
Explanation:
As the build-in function strlen is in the disabled list in the php.ini file, the function-exists() function consider them non-exist.
Practical Usages of PHP function_exists() function:
- To protect your code breaking, we use function_exists() function in our web applications.
Notes on PHP function_exists() function:
- function_exists() function doesn’t return a function if is in the disable function list in the php.ini file. To see the disabled function list in php.ini file, look for the line “disable_functions =”. Here, functions are listed. To disable strlen() function, add this disable_functions = strlen. To add more function in this list, use comma. Check example 3.
PHP Version Support:
PHP 4, PHP 5, PHP 7, PHP 8
Summary: PHP function_exists() Function
function_exists() is a built-in PHP “function handling” function that is used to check whether a built-in or user defined function is disabled or not.