String Interpolation & Heredoc/Nowdoc
Also Known As
TL;DR
Explanation
PHP offers four string literal syntaxes. Double-quoted strings interpolate simple variables ($name), array elements ({$arr['key']}), and complex expressions (${expr}). Heredoc (<<<EOT ... EOT) behaves like a double-quoted string across multiple lines — useful for SQL, HTML templates, and email bodies. Nowdoc (<<<'EOT' ... EOT) is the heredoc equivalent of single-quoted strings — no interpolation at all, ideal when the content contains dollar signs or backslashes that shouldn't be treated as escape sequences. PHP 8.3 tightened heredoc/nowdoc indentation rules: the closing marker's indentation defines the strip amount. Avoid interpolation of user data into SQL strings — use prepared statements regardless of how readable $query = "SELECT * FROM users WHERE id=$id" looks.
Common Misconception
Why It Matters
Common Mistakes
- Interpolating user input directly into SQL queries — even inside a string, this is SQL injection.
- Complex expressions in strings: "User {$user->getName()}" — use concatenation or sprintf for clarity.
- Confusing single-quoted (no interpolation) and double-quoted (interpolation) strings.
- Not using curly brace syntax for array access: "Hello $user[name]" vs "Hello {$user['name']}".
Code Examples
$q = "SELECT * FROM users WHERE email='$email'"; // SQLi via interpolation
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);