We do not always know that a function exists before we try to invoke it. Different builds of the PHP engine may include different functionality, and if you are writing a script that may be run on multiple servers, you might want to verify that key features are available. For instance, you might want to write code that will use MySQL if MySQL-related functions are available but simply log data to a text file otherwise.
You can use function_exists() to check for the availability of a function. function_exists() requires a string representing a function name. It returns true if the function can be located and false otherwise.
Listing 7.14 shows function_exists() in action and illustrates some of the other topics we have covered in this chapter.
Listing 7.14. Testing for a Function's Existence
We define two functions, tagWrap() (line 2) and underline() (line 11). The tagWrap() function accepts three strings: a tag, the text to be formatted, and an optional function name. It returns a formatted string. The underline() function requires a single argumentthe text to be formattedand returns the text wrapped in <span> tags with appropriate style attributes.
When we first call tagWrap() on line 15, we pass it the character b and the string "make me bold". Because we haven't passed a value for the function argument, the default value (an empty string) is used. On line 3, we check whether the $func variable contains characters, and, if it is not empty, we call function_exists() to check for a function by that name. Of course, in this case, the $func variable is empty, so we wrap the $txt variable in <b> tags in the else clause on lines 67 and return the result.
We call tagWrap() on line 17 with the string 'i', some text, and a third argument: "underline". function_exists() finds a function called underline() (line 11), so it calls this function and passes the $txt argument variable to it before any further formatting is done. The result is an italicized, underlined string.
Finally, on line 19, we call tagWrap(), which wraps text in quotation entities. It would be quicker to simply add the entities to the text to be transformed ourselves, but this example serves to illustrate the point that function_exists() works as well on anonymous functions as it does on strings representing function names.
Put these lines into a text file called exists.php and place this file in your web server document root. When you access this script through your web browser, it should look like Figure 7.8.
Figure 7.8. Output of exists.php.