Unused Private Field
ID |
php.unused_private_field |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Php |
Tags |
CWE:563, code_smell, dead-code |
Description
Reports a private property that is never read or written anywhere in its declaring class. A
private property is only reachable from inside its own class, so one whose name never appears in
a $this→name, self::$name or static::$name access is dead code.
Rationale
A field that nothing ever touches still costs memory on every instance, shows up in dumps and serialization, and misleads the reader into thinking it carries state. Most often an unused private property is a leftover from a refactoring that moved the logic elsewhere but forgot to delete the declaration. Removing it makes the class smaller and its real state easier to follow.
Constructor-promoted properties (__construct(private int $x)) are treated exactly like ordinary
private fields, so a promoted property the class never consults is flagged too.
<?php
class Cart
{
private array $items = []; // OK — used below
private float $unusedTotal; // FLAW — never read or written
public function add(string $sku): void
{
$this->items[] = $sku; // reads/writes $items
}
}
When the class accesses properties through a dynamic name ($this→$name) or a variable-scope
built-in (compact, extract, get_defined_vars), the whole class is skipped because a
property could be reached without a literal name.