Current Location: Home> Latest Articles> PHP String Definition Methods: Single Quotes, Double Quotes, Heredoc, Nowdoc

PHP String Definition Methods: Single Quotes, Double Quotes, Heredoc, Nowdoc

M66 2025-07-18

PHP String Definition Methods: Single Quotes, Double Quotes, Heredoc, Nowdoc

In PHP programming, there are various ways to define strings, each suited to different scenarios. This article introduces four common methods for defining strings: single quotes, double quotes, Heredoc, and Nowdoc.

Defining Strings with Single Quotes

Single quotes are the simplest way to define strings in PHP. When using single quotes, any single quote inside the string must be escaped (with a backslash).

Example:


$str = 'Hello World';
$str_with_quote = 'I said, "Hello World"';

Defining Strings with Double Quotes

Double quotes work similarly to single quotes, but with the key difference that variables inside the string are parsed and replaced with their values.

Example:


$name = 'John';
$greeting = "Hello $name!";

Heredoc Syntax

Heredoc is a syntax for defining multi-line strings, useful for handling large text blocks. In Heredoc, the string's end delimiter can be any custom identifier, and variables inside the string are parsed.

Example:


$html = <<<HTML
<html>
    <body>Hello World</body>
</html>
HTML;

Nowdoc Syntax

Nowdoc is similar to Heredoc but doesn't parse any variables within the string. Everything inside the Nowdoc is treated as raw text. The delimiter for Nowdoc must be enclosed in either single or double quotes.

Example:


$name = 'John';
$greeting = <<<'GREETING'
Hello $name!
GREETING;

These are the four common methods for defining strings in PHP, each suited to specific use cases. Mastering these techniques will help you work more efficiently with strings in PHP development.