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.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.28, 8.4.1 - 8.4.14, 8.5.0 - 8.5.1
C::__construct() ok ok C::__construct() ok ok ok C::__construct() ok
Output for 8.4.15
/bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.35' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.34' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15)
Process exited with code 1.

preferences:
219.52 ms | 407 KiB | 5 Q