A Function with an OPTIONAL ARGUMENT

Chapter 7 #143 - Martha's CIS 52

ASSIGNMENT/EXPLANATION

This example is very similar to #142-fontwrap.php, but it adds an optional default argument. "By assigning a value to an argument variable within the function definition's parentheses, you can make the $fontsize argument optional. If the function call doesn't define an argument for this argument, the value you have assigned to the argument is used instead." (143) This is clearly seen in the fact that the 3 lines for smaller text do NOT create smaller text - without the optional argument for $fontsize, the code uses the default value of "12 pt".

NOTICE: "You can create as many optional arguments as you want, but when you've given an argument a default value, all subsequent values should also be given defaults." (143)

Exercise

A Heading
some body text
smaller body text
even smaller body text

CODE

<?php 
function fontWrap($txt, $fontsize = "12pt") {
echo "<span style=\"font-size:$fontsize\">".$txt."</span>";
}
fontWrap("A Heading<br />", "24pt");
fontWrap("some body text<br />");
fontWrap("smaller body text<br />");
fontWrap("even smaller body text<br />");
?>