Define Argument with default value in PHP

Description

The following code shows how to define Argument with default value.

Example


/* ww w  .ja v a2  s  .c  om*/
<?php
  function printColor($text, $color="black", &$count=NULL)
  {
    //print the text with style
    print("<span style=\"color: $color\">" . "$text</span>");

    //if given a count, increment it
    if(isset($count))
    {
      $count++;
    }
  }

  //call with one argument
  printColor("This is black text");
  print("<br>\n");

  //override default color
  printColor("This is blue text", "blue");
  print("<br>\n");

  //pass in count reference
  $c = 0;
  printColor("This is red text", "red", $c);
  print("<br>\n");

  printColor("This is green text", "green", $c);
  print("<br>\n");
  print("Count: $c<br>");
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition