[Previous] [Contents] [Next]


Default argument values

PHP allows functions to be defined with default values for arguments. A default value is simply supplied in the argument list using the = sign. Consider the modified heading( ) function described earlier:

function heading($text, $headingLevel = 2)
{
  switch ($level)
  case 1:
    $result = "<h1>" . ucwords($text) . "</h1>";
    break;

  case 2:
    $result = "<h2>" . ucwords($text) . "</h2>";
    break;

  case 3:
    $result = "<h3>" . ucfirst($text) . "</h3>";
    break;

  default:
    $result = "<p><b>" . ucfirst($text) . "</b>";

  return($result);
}

$test = "user defined functions";
echo heading($test);

When calls are made to the heading( ) function, the second argument can be omitted, and the default value 2 is assigned to the $headingLevel variable.


[Previous] [Contents] [Next]