如何解决是否可以在 PHP 中取消设置静态属性?
我正在尝试使用具有静态方法和属性的类而不是单例。一切正常,直到我不得不取消设置一个静态属性,并且我的 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 举报,一经查实,本站将立刻删除。