[Previous] [Contents] [Next]

Argument Types and Return Types

The argument and return types of a function aren't declared when the function is defined. PHP allows arguments of any type to be passed to the function, and as with variables, the return type is determined when a result is actually returned. Consider a simple function that divides two numbers:

function divide($a, $b)
{
    return ($a/$b);
}
$c = divide(4, 2);  // assigns an integer value = 2
$c = divide(3, 2);  // assigns a float value = 1.5
$c = divide(4.0, 2.0); // assigns a float value = 2.0

If the types of arguments passed to the function are critical, they should be tested as shown earlier in Section 2.1.3.

Variable Scope

Variables used inside a function are different from those used outside a function. The variables used inside the function are limited to the scope of the function (there are exceptions to this rule, which are discussed later in this section). Consider an example that illustrates variable scope:

function doublevalue($var)
{
  $temp = $var * 2;
}
$variable = 5;
doublevalue($variable);
echo "\$temp is: $temp";

This example outputs the string:

$temp is:

and no value for $temp. The scope of the variable $temp is local to the function doublevalue( ) and is discarded when the function returns.

The PHP script engine doesn't complain about undeclared variable being used. It just assumes the variable is empty. However, this use of an undefined variable can be detected using the error-reporting settings discussed later, in Section 2.12.

If you want to use a value that is local to a function elsewhere in a script, the easiest way to do so is to return the value of the variable. This example achieves this:

function doublevalue($var)
{
  $returnVar = $var * 2;
  return($returnVar);
}
$variable = 5;
$temp = doublevalue($variable);
echo "\$temp is: $temp";

The example prints:

$temp is: 10

You could have still used the variable name $temp inside the function doublevalue( ). However, the $temp inside the function is a different variable from the $temp outside the function. The general rule is that variables used exclusively within functions are local to the function, regardless of whether an identically named variable is used elsewhere. There are two exceptions to this general rule: variables passed by reference and those declared global in the function aren't local to the function.

[Previous] [Contents] [Next]