问题描述
我正在尝试使用具有静态方法和属性的类而不是单例。一切正常,直到我不得不取消设置一个静态属性,并且我的 PHP 8.0 抛出了一个错误。我需要这个,因为在某些时候可能没有设置属性,用于延迟加载或状态重置。
检查此示例代码:
<?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();
}
它显示的错误消息是:Fatal error: Uncaught Error: Attempt to unset static property TextContainer::$text
。
我不希望使用某种解决方法,例如将 null
分配给属性,因为我喜欢强类型,这会迫使我将属性提示为 string|null
。
有什么想法吗?提前致谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)