Missing Property Type
ID |
php.missing_property_type |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Php |
Tags |
code_smell, type-safety |
Description
Reports class properties declared without a type. Typed properties have existed since PHP 7.4
(public int $count;); an untyped property falls back to the implicit mixed type, so the engine
cannot enforce what it holds.
Rationale
An untyped property can be assigned any value at any point, which makes the class state hard to
reason about and lets an inconsistent value live silently until it causes a fault elsewhere. A
declared type turns an invalid assignment into an immediate error and documents the property’s
purpose. Constructor-promoted properties (__construct(public $label)) are properties too and are
held to the same standard, and the legacy var $x; form is flagged because it is both untyped and
outdated style.
<?php
class Account
{
public $balance; // FLAW — property has no type declaration
private string $owner; // OK — typed property
public function __construct(
public $label, // FLAW — promoted property has no type
private int $id // OK — promoted typed property
) {
}
}
Remediation
Declare the property’s type before the variable name: a scalar (int, float, string, bool),
a class or interface, a nullable type (?Type), or a union (int|string). Convert var $x;
declarations to a typed private/protected/public form.