Search code examples
phpphp-7.4php-8

How to remove property from object in PHP 7.4+


How to remove property if property has type.

unset() working if property does not have type.

class A
{
  public string $a;
  public $b;
}

$o = new A();
unset($o->a);
unset($o->b);

// object(A)#1 (0) {
//   ["a"]=>
//   uninitialized(string)
// }

Solution

  • According to the RFC on typed properties:

    If a typed property is unset(), then it returns to the uninitialized state. While we would love to remove support for the unsetting of properties, this functionality is currently used for lazy initialization by Doctrine, in combination with the functionality described in the following section.