3v4l.org

run code in 300+ PHP versions simultaneously
<?php final class SingletonUtil { /** * @var mixed[] * Format: $[$key] =& $variable */ private static $variables = []; /** * @var mixed[] */ private static $defaults = []; /** * @param string $key * @param mixed $variable * @param mixed $value * @param mixed|null $default * Default value to be used when resetting. * * @return mixed */ public static function init($key, &$variable, $value, $default = NULL) { self::$variables[$key] =& $variable; self::$defaults[$key] = $default; return $variable = $value; } /** * @param string ($key_or_null */ public static function reset($key_or_null = NULL) { if (NULL === $key_or_null) { foreach (self::$variables as $key => $variable) { self::$variables[$key_or_null] = self::$defaults[$key_or_null]; } } elseif (array_key_exists($key_or_null, self::$variables)) { self::$variables[$key_or_null] = self::$defaults[$key_or_null]; } } } class C { function __construct() { print __METHOD__ . "()\n"; } } /** * @return mixed */ function singleton_test() { // This would otherwise use drupal_static_fast pattern. // But this is even faster. static $cache; return $cache ?: SingletonUtil::init( __FUNCTION__, $cache, new C()); } function assert_or_ok($boolval) { if (!$boolval) { assert(FALSE); exit(); } print "ok\n"; } $obj = singleton_test(); assert_or_ok($obj instanceof C); assert_or_ok($obj === singleton_test()); SingletonUtil::reset('singleton_test'); assert_or_ok($obj !== singleton_test()); $obj = singleton_test(); assert_or_ok($obj instanceof C); assert_or_ok($obj === singleton_test()); SingletonUtil::reset('singleton_test'); assert_or_ok($obj !== singleton_test());
Output for 7.1.25 - 7.1.27, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
C::__construct() ok ok C::__construct() ok ok ok C::__construct() ok
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 C::__construct() ok ok C::__construct() ok ok ok C::__construct() ok

preferences:
141.18 ms | 402 KiB | 160 Q