Created
September 23, 2011 15:38
-
-
Save StanAngeloff/1237688 to your computer and use it in GitHub Desktop.
PHP static wierdness
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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