Searching...
Friday 14 June 2013

PHP Basics - Part 5 :: Variables Part 3 :: Scope 2

Function Parameters

In PHP, as in many other programming languages, any function that accepts arguments must declare those arguments in the function header. Although those arguments accept values that come from outside of the function, they are no longer accessible once the function has exited.

Note This section applies only to parameters passed by value and not to those passed by reference. Parameters passed by reference will indeed be affected by any changes made to the parameter from within the function.

Function parameters are declared after the function name and inside parentheses. They are declared much like a typical variable would be:

// multiply a value by 10 and return it to the caller
function x10 ($value) {
$value = $value * 10;
return $value;
}

Keep in mind that although you can access and manipulate any function parameter in the function in which it is declared, it is destroyed when the function execution ends.


Static Variables

The final type of variable scoping to discuss is known as static. In contrast to the variables declared as function parameters, which are destroyed on the function’s exit, a static variable does not lose its value when the function exits and will still hold that value if the function is called again. You can declare a variable as static simply by placing the keyword static in front of the variable name, like so:

STATIC $somevar;

Consider an example:


function keep_track() {
static $count = 0;
$count++;
echo $count;
echo "<br />";
}
keep_track();
keep_track();
keep_track()

What would you expect the outcome of this script to be? If the variable $count was not designated to be static (thus making $count a local variable), the outcome would be as follows:

1
1
1

However, because $count is static, it retains its previous value each time the function is executed. Therefore, the outcome is the following:

1
2
3

Static scoping is particularly useful for recursive functions, a powerful programming concept in which a function repeatedly calls itself until a particular condition is met.


0 comments:

Post a Comment

 
Back to top!