In PHP heredoc, variables are automatically parsed (interpreted) inside the string, just like in double-quoted strings ("..."). You don't need any special syntax—just include the variable name directly.
Basic Variable Parsing in Heredoc
$name = "John";
$age = 30;
$message = <<<EOT
Hello, $name!
You are $age years old.
EOT;
echo $message;
Output:
Hello, John!
You are 30 years old.
Handling Complex Variables (Arrays, Objects)
If you need to parse array elements or object properties, use curly braces {} for clarity:
$user = ["name" => "Alice", "age" => 25];
$info = <<<EOT
User: {$user['name']}
Age: {$user['age']}
EOT;
echo $info;
Output:
User: Alice
Age: 25
Escaping Variables (Prevent Parsing)
If you want to prevent variable parsing, use nowdoc (single quotes around the identifier):
$name = "Bob";
$text = <<<'EOT'
This is a nowdoc.
Variables like $name are NOT parsed.
EOT;
echo $text;
Output:
This is a nowdoc.
Variables like $name are NOT parsed.
Parsing Functions & Expressions
You can also execute functions inside heredoc using {}:
$price = 100;
$discount = 0.2;
$receipt = <<<EOT
Total: {$price}
Discount: {$price * $discount}
Final Price: {$price - ($price * $discount)}
EOT;
echo $receipt;
Output:
Total: 100
Discount: 20
Final Price: 80
Key Takeaways
✅ Variables are parsed automatically (like double-quoted strings).
✅ Use {} for complex variables (arrays, objects, expressions).
✅ Use nowdoc (<<<'EOT') to disable parsing.
✅ Works with functions and calculations inside {}.
Would you like an example with HTML templates or SQL queries? 🚀