WOW! Could there be a more fabulous function? This one adds HTML tags around text to style it for output to the browser page. However, that is not the main concept being demonstrated. A key component of this exercise is to see that the function exists before executing the function itself. Why does this matter? "Different builds of the PHP engine might 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." (145)
This test for the availability of a function is performed by function_exists(). This function "requires a string representing a function name. It returns true if the function can be located and false otherwise." (145) In addition to using this built-in PHP function, this example defines two other functions:
When your first call tagWrap(), you pass the character 'b' and a string, but, "Because you haven't passed a value for the function argument, the default value (an empty string) is used." After a check if the function contains characters, and if the function wrapText() exists, the $txt variable is wrapped in <b> tags, since the $func variable is empty, and the line is returned (printed on the page).
Next, the code calls tagWrap() which contains the 'i' character, some text to be styled, and a 3rd function. Since function_exists() discovers there is indeed a function called "underline()", 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.
The third and final call of tagWrap() contains the 'i' character again, and some text to be formatted, but this time it includes an anonymous function in the position of the 3rd argument. An anonymous function is one that has no specified name, and in this case is created by the create_function() function. The point of this example is to show that function_exists() does not requre strings representing function names in order to do it's job.
<?php
function tagWrap($tag, $txt, $func = "") {
if ((!empty($txt)) && (function_exists($func))) {
$txt = $func($txt);
return "<".$tag.">".$txt."</".$tag."><br />";
} else {
return "<b>".$txt."</b><br />";
}
}
function underline($txt) {
return "<span style=\"text-decoration:underline;\">".$txt."</span>";
}
echo tagWrap('b', 'make me bold');
echo tagWrap('i', 'underline me too', "underline");
echo tagWrap('i', 'make me italic and quote me', create_function('$txt', 'return ""$txt"";'));
?>