PHP Variables
Persisting a Local Variable’s Value Across Function Invocations
Problem
You want a local variable to retain its value between invocations of a function.Solution
Declare the variable as static:function track_times_called() {
static $i = 0;
$i++;
return $i;
}
Discussion
Inside a function, declaring a variable static causes its value to be remembered by the function. So, if there are subsequent calls to the function, you can access the value of the saved variable. The check_the_count() function shown in Example uses static variables to keep track of the strikes and balls for a baseball batter.Example check_the_count()
function check_the_count($pitch) {
static $strikes = 0;
static $balls = 0;
switch ($pitch) {
case 'foul':
if (2 == $strikes) break; // nothing happens if 2 strikes
// otherwise, act like a strike
case 'strike':
$strikes++;
break;
case 'ball':
$balls++;
break;
}
if (3 == $strikes) {
$strikes = $balls = 0;
return 'strike out';
}
if (4 == $balls) {
$strikes = $balls = 0;
return 'walk';
}
return 'at bat';
}
$pitches = array('strike', 'ball', 'ball', 'strike', 'foul','strike');
$what_happened = array();
foreach ($pitches as $pitch) {
$what_happened[] = check_the_count($pitch);
}
// Display the results
var_dump($what_happened);
Example prints:
array(6) {
[0]=>
string(6) "at bat"
[1]=>
string(6) "at bat"
[2]=>
string(6) "at bat"
[3]=>
string(6) "at bat"
[4]=>
string(6) "at bat"
[5]=>
string(10) "strike out"
}
In check_the_count(), the logic of what happens to the batter depending on the pitch count is in the switch statement inside the function. You can instead return the number of strikes and balls, but this requires you to place the checks for striking out, walking, and staying at the plate in multiple places in the code.
Though static variables retain their values between function calls, they do so only during one invocation of a script. A static variable accessed in one request doesn’t keep its value for the next request to the same page.
No comments:
Post a Comment