Variable As String
ID |
php.variable_as_string |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Php |
Tags |
code_smell, strings |
Description
Reports two pointless ways of turning a single value into a string: concatenating it with an empty
string literal ('' . $x or $x . '') and wrapping a single variable in a double-quoted
interpolated string ("$x"). Both produce the value already stringified, with no surrounding
text or other operand.
Rationale
'' . $x and "$x" both coerce $x to a string, exactly as (string) $x does, but they hide
that intent behind a concatenation or an interpolation and add an unnecessary allocation. The cast
form states plainly that a string conversion is happening, reads better in code review, and avoids
the small runtime overhead of building a temporary string. A concatenation with a non-empty
literal ('id-' . $x) or an interpolation with surrounding text or a second variable
("value: $x", "$x$y") is a real string build and is left alone.
<?php
$a = '' . $x; // FLAW - empty-string concatenation to stringify
$b = $x . ''; // FLAW - same idiom, other order
$c = "$x"; // FLAW - single interpolated variable as whole string
$d = (string) $x; // OK - explicit cast
$e = "value: $x"; // OK - interpolation with surrounding text
$f = $x . $y; // OK - real concatenation of two operands
Remediation
Replace the idiom with an explicit cast, (string) $x, or with strval($x) when a callable is
needed. Keep concatenation and interpolation for cases that actually combine the value with other
text.