1.2.374. Don’t Unset Properties

Don’t unset properties. They would go undefined, and raise warnings of undefined properties, even though the property is explicitly defined in the original class.

When getting rid of a property, assign it to null. This keeps the property defined in the object, yet allows existence check without errors. This analysis works on properties and static properties. It also reports magic properties being unset.

Thanks for Benoit Burnichon for the original idea.

<?php

class Foo {
    public $a = 1;
}

$a = new Foo();

var_dump((array) $a) ;
// la propriété est reportée, et null
// ['a' => null]

unset($a->a);

var_dump((array) $a) ;
//Empty []

// Check if a property exists
var_dump($a->b === null);

// Same result as above, but with a warning
var_dump($a->c === null);

?>

1.2.374.1. Suggestions

  • Set the property to null or its default value

  • Make the property an array, and set/unset its index

1.2.374.2. Specs

Short name

Classes/DontUnsetProperties

Rulesets

All, Analyze, CE, CI-checks, Top10, php-cs-fixable

Exakat since

1.2.3

PHP Version

All

Severity

Major

Time To Fix

Slow (1 hour)

Precision

Very high

Features

property

Examples

Vanilla, Typo3

Available in

Entreprise Edition, Community Edition, Exakat Cloud