Field Name Matches Class
ID |
php.field_name_matches_class |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Code Smell |
Language |
Php |
Tags |
code_smell, naming |
Description
Reports a property that is both named like its declaring class and declared with that class as its
type — a genuinely self-typed field. Both regular and constructor-promoted properties are checked;
the type comparison is case-insensitive and ignores a leading ? or \.
Rationale
A property typed as its own class and named after it (class Node { private Node $node; }) blurs
the distinction between the type and one of its values and usually signals a confused design. A
mere name coincidence is not a defect, so the rule requires the declared type to match: a
principal-value field such as class State { private $state; } or a differently-typed field such
as class Json { private string $json; } is idiomatic and is left alone.
<?php
class Node
{
private Node $node; // FLAW — self-typed field named like the class
private string $label; // OK — distinct name
}
class State
{
private $state; // OK — principal-value field, no type
}
class Json
{
private string $json; // OK — name matches class but type is string
}
Remediation
Rename the property to describe the value it holds rather than the type that owns it, for
example $next, $parent, or $child.