- assert: documentation ( source)
<?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());