Skip to content

Instantly share code, notes, and snippets.

@martynchamberlin
Last active August 29, 2015 14:03
Show Gist options
  • Save martynchamberlin/0db6f0e3ca897db61c4f to your computer and use it in GitHub Desktop.
Save martynchamberlin/0db6f0e3ca897db61c4f to your computer and use it in GitHub Desktop.
PHP overloads the `static` keyword. In instance variables, it means the classical OOP usage. In local variables (stack instead of heap) it means something else. This code demonstrates that something else.
<?php
function get_random_num( $start = 1, $finish = 2 )
{
static $rand;
if ( ! isset( $rand ) )
{
$rand = rand( $start, $finish );
}
return $rand;
}
for ( $i = 0; $i < 10; $i++ )
{
printf( "%s ", get_random_num( $i, $i + 20 ) ); // Prints the same random number to the screen 10 times
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment