0
0
PHPprogramming~15 mins

Heredoc and nowdoc syntax in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Heredoc and Nowdoc Syntax in PHP
📖 Scenario: You are creating a simple PHP script to store and display multi-line text messages. These messages include variables and special characters, so you want to use the best way to write them clearly.
🎯 Goal: Build a PHP script that uses heredoc and nowdoc syntax to store multi-line strings, then display them.
📋 What You'll Learn
Create a variable using heredoc syntax with a multi-line string that includes a variable.
Create a variable using nowdoc syntax with a multi-line string that includes a variable but does not parse it.
Print both variables to show the difference.
💡 Why This Matters
🌍 Real World
Heredoc and nowdoc syntax help PHP developers write multi-line strings clearly, especially when working with templates, emails, or large text blocks.
💼 Career
Understanding these syntaxes is useful for PHP developers working on web applications, content management systems, or any project that involves dynamic text generation.
Progress0 / 4 steps
1
Create a heredoc string with a variable
Create a variable called name and set it to the string "Alice". Then create a variable called heredocText using heredoc syntax that contains the text: Hello, $name! Welcome to heredoc syntax. on one line and This is a multi-line string. on the next line.
PHP
Need a hint?

Remember, heredoc starts with <<<EOD and ends with EOD; on its own line.

2
Create a nowdoc string with a variable
Create a variable called nowdocText using nowdoc syntax that contains the text: Hello, $name! This will not parse the variable. on one line and This is also a multi-line string. on the next line.
PHP
Need a hint?

Nowdoc syntax uses single quotes around the identifier like <<<'EOD'.

3
Print both heredoc and nowdoc variables
Use echo to print the variable heredocText followed by a newline, then print the variable nowdocText.
PHP
Need a hint?

Use echo and add a newline character "\n" after printing heredocText.

4
Run the script and observe output
Run the PHP script and observe the output. The first printed text should show the variable $name replaced by Alice. The second printed text should show the variable name $name literally, without replacement.
PHP
Need a hint?

The heredoc string replaces $name with Alice, but the nowdoc string shows $name as text.