I'm trying to use classes with static methods and properties instead of Singletons. Everything was ok until I had to unset a static property, and my PHP 8.0 threw an error. I need this because the property may not be set at some point, for lazy loading or state reset.
Check this example code:
<?php
declare(strict_types=1);
final class
TextContainer
{
private static string $text;
public static function has():bool
{
return isset(self::$text);
}
public static function getAfterHas():string
{
return self::$text;
}
public static function set(string $v):void
{
self::$text = $v;
}
public static function unset():void
{
unset(self::$text);
}
}
TextContainer::set('foo');
if (TextContainer::has())
{
echo TextContainer::getAfterHas();
}
TextContainer::unset();
if (TextContainer::has())
{
echo TextContainer::getAfterHas();
}
The error message it shows is: Fatal error: Uncaught Error: Attempt to unset static property TextContainer::$text
.
I would prefer not using some kind of workaround like assigning null
to the property, because I like the strong typing, and that would force me to type hint the property as string|null
.
Any ideas? Thank you in advance.