John Davidson

properties - Is it possible to unset a static property in PHP?

0 comments
Message:


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.



My Answer:
No, it is not possible to unset a static property in PHP. Once a static property is set, it cannot be unset. You can set it to null or another value to simulate unsetting it, but you cannot actually unset it.

In your case, you can set the static property to null when you want to simulate unsetting it. For example:

php
class Example {
public static $property = null;

public static function unsetProperty() {
self::$property = null;
}
}

Example::$property = 'value';
echo Example::$property; // Output: value

Example::unsetProperty();
echo Example::$property; // Output: null

Rate this post

3 of 5 based on 5870 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us