We can check built in function or user defined functions before using them. The built in function function_exists checks this and returns true of false. It takes one string input and returns Boolean output. Here is an example.
if(function_exists(is_int)){
echo " Yes this function is available to use ";
}else{
echo " Sorry , this is not available to use " ;
}
In the above code we have used is_int() which is a built in function in PHP, so we will get the output as this.
Yes this function is available to use
User defined functions
<?Php
function my_function($var1,$var2,$var3){
$var=$var1+$var2+$var3;
return $var;
}
echo my_function(5,6,8); // Output 19
if(function_exists(is_int)){
echo " <br>Yes <i>my_function</i> is available to use ";
}else{
echo " <br>Sorry , <i>my_function</i> is not available to use " ;
}
?>
if (function_exists('mysqli_connect')) {
echo "mysqli is installed";
}else{
echo " Enable Mysqli support in your PHP installation ";
}
Example: Checking Custom Function
function myFunction() {
echo "Function exists!";
}
if (function_exists('myFunction')) {
myFunction(); // Output: Function exists!
} else {
echo "Function not found!";
}
Example: Preventing Fatal Errors
if (function_exists('nonexistentFunction')) {
nonexistentFunction(); // Avoids fatal error
} else {
echo "Function does not exist!";
}
### Description: Custom Functions: Ensures that the custom function exists before executing it.
Fatal Error Prevention: Prevents runtime fatal errors by checking the function's existence.
Namespaces: When working with namespaces, ensure the function exists in the correct scope.
### Example: Working with Namespaces
namespace MyNamespace;
function customFunc() {
echo "Namespace Function";
}
if (function_exists('MyNamespace\\customFunc')) {
customFunc(); // Output: Namespace Function
}