[Previous] [Contents] [Next]

Assigning PHP variables by reference

Referencing with the ampersand can also be used when assigning variables, which allows the memory holding a value to be accessed from more than one variable. This example illustrates the idea:

$x = 10;
$y = &$x;
$y++;
echo $x;
echo $y;

Here's how it prints:

11
11

Because $y is a reference to $x, any change to $y affects $x. In effect, they are the same variable. So, by adding 1 to $y, you also add 1 to $x, and both are equal to 11.

The reference $y can be removed with:

unset($y);

This has no effect on $x or its value.

Functions 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]