Skip to content

Instantly share code, notes, and snippets.

@StanAngeloff
Created September 23, 2011 15:38
Show Gist options
  • Save StanAngeloff/1237688 to your computer and use it in GitHub Desktop.
Save StanAngeloff/1237688 to your computer and use it in GitHub Desktop.
PHP static wierdness
<?php
# Example with function
function print_first_value(&$value)
{
static $keep = NULL;
if ($keep === NULL) {
print "Setting $value.\n";
$keep = &$value; # NOTE: using $value by reference
}
print preg_replace('#\s+#', ' ', var_export($keep, TRUE)) . "\n";
}
$value1 = 1; print_first_value($value1); # prints 1 as expected
$value2 = 2; print_first_value($value2); # prints 2!
<?php
# Example with a class wrapper
class Print_
{
static $keep = NULL;
static function first_value(&$value)
{
if (self::$keep === NULL) {
print "Setting $value.\n";
self::$keep = &$value; # NOTE: using $value by reference
}
print preg_replace('#\s+#', ' ', var_export(self::$keep, TRUE)) . "\n";
}
}
$value1 = 1; Print_::first_value($value1); # prints 1 as expected
$value2 = 2; Print_::first_value($value2); # prints 1 as expected
<?php
# Example with function and static using an array()
function print_first_value(&$value)
{
static $keep = array();
if (sizeof ($keep) < 1) {
print "Setting $value.\n";
$keep[] = &$value;
}
print preg_replace('#\s+#', ' ', var_export($keep, TRUE)) . "\n";
}
$value1 = 1; print_first_value($value1); # prints 1 as expected
$value2 = 2; print_first_value($value2); # prints 1 as expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment