Variable Initialization
ID |
php.variable_initialization |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Php |
Tags |
reliability, uninitialized-variable |
Description
Reports a local variable that is read before it is ever assigned inside the same function
body. Reading an uninitialised variable yields null together with a runtime warning, and
almost always signals a typo in the variable name or a missing assignment.
Rationale
The analysis is deliberately conservative to avoid false positives on dynamic PHP code. For
each function a single statement-order pass compares the position of a variable’s first read
against its first write; a variable is flagged only when a read precedes every write.
Parameters, closure use (…) captures, $this, superglobals, global and static
declarations, foreach targets, list() / array-destructuring targets, and occurrences
inside isset(), empty() or is_null() are all treated as already initialised. Functions
that call extract() or include another file are skipped entirely.
<?php
function totalWithTax(float $price): float
{
$total = $price * $rate; // FLAW - $rate read before any assignment
$rate = 1.21;
return $total;
}
function safeTotal(float $price): float
{
$rate = 1.21; // OK - assigned before use
return $price * $rate;
}
Remediation
Assign the variable a sensible default before its first use, or fix the typo if the name was meant to refer to a variable that already exists.