How to check if a function exists in PHP?

 

If you are writing a PHP code or a Plugin you should be very careful at using functions, why means that the function you are using might not be there in the previous version of PHP such as PHP 4.

Lets take an instance, there are plenty of new function added in PHP 5 which was not there in PHP 4, one of that is scandir(), This function is introduced only on PHP 5, so what happens when someone tried to execute this function in PHP 4 server?. Obviously, they are going to receive errors.

So, to avoid these things there is a default PHP function (function_exists()) which will let us know whether any function is present or not. If the function exists it will return true otherwise false.

This helps to check the existence of default functions as well custom functions:

Example 1 : Checking a default PHP function:

The above script will print “yes exists” if the scandir() function exists otherwise it will print “no not exists”

 

Example 2 : Checking a custom PHP function which is written by us (our own function):

The second example is also same if the custom function exists it will return “yes” otherwise “no”

 

 

 

Related Posts

Leave a Reply