Variable Substitution

ID

php.variable_substitution

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Php

Tags

code_smell, deprecation

Description

Reports the complex ${…​} variable-substitution syntax inside interpolating strings, such as "Hello ${name}" or "${ getName() }". This form was deprecated in PHP 8.2 and is scheduled for removal in a future major version.

Rationale

PHP offers several ways to embed a variable in a double-quoted string or heredoc. The ${expr} form is ambiguous: ${name} looks like a variable reference but actually evaluates the identifier name as a constant expression and then dereferences the resulting variable variable, which surprises most readers. Because of that ambiguity it was deprecated in PHP 8.2 and emits a deprecation notice; code that relies on it will stop working when the syntax is removed. The curly-brace form {$expr} and the simple form $name are unambiguous and remain fully supported.

<?php
function greet(string $name): string
{
    $a = "Hello ${name}";       // FLAW — deprecated ${} substitution
    $b = "Hello ${ getName() }";// FLAW — deprecated ${} substitution

    $c = "Hello {$name}";       // OK — curly-brace style is supported
    $d = "Hello $name";         // OK — simple interpolation
    $e = 'Raw ${name}';         // OK — single quotes never interpolate
    return $a . $b . $c . $d . $e;
}

Remediation

Rewrite the substitution using the curly-brace form {$expr} (which accepts arbitrary expressions) or, for a bare variable, the simple form $name. For example, replace "Hello ${name}" with "Hello {$name}".