PHP heredoc so với nowdoc

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping

Look that the difference between those 2 is that nowdocs uses single quotes when defining the tag (that can be anything you want) and heredocs doesn’t

and syntax, that helped to use multi-line strings had rigid requirements that the ending identifier should be the first string appearing in a new line

Ví dụ

$foo = <<<IDENTIFIER
the crazy dog jumps over the lazy fox
"foo" bar;
IDENTIFIER

In here, the last IDENTIFIER must be the first string in a new line for this to work. In addition, there must not be any other characters after the last IDENTIFIER (other than a semi colon, which is optional)

RFC cho PHP 7. 3 suggested to remove the requirement above with the goal of making the code more readable. Before this RFC, one had to break the indentation used in the rest of the code just so here/now doc tokens can be used. The RFC suggests making these changes to heredoc/nowdoc syntax

  1. The ending token no longer needs to be the first string of the line
  2. The ending token can be indented with spaces or tabs
  3. The white-space characters (space or tab) must not be intermixed. If you do so, you will get a Parse error: Invalid indentation - tabs and spaces cannot be mixed in . on line ..
  4. The exact number of spaces/tabs used in the ending token will be stripped off from the contents within the heredoc/nowdoc expression
  5. If the number of white-space characters used in the ending token is greater than any of the white-space characters within the expression, you will get Parse error: Invalid body indentation level (expecting an indentation level of at least ..) in . on line ..
  6. You can add more expressions after the ending token without any errors
$foo = ['foo', 'bar', <<<EOT
  baz
    -  hello world! --
  ahoy
  EOT, 'qux', 'quux'
];

var_dump($foo);

the output would be

array(5) {         
  [0]=>            
  string(3) "foo"  
  [1]=>            
  string(3) "bar"  
  [2]=>            
  string(29) "baz  
  -  hello world! --
ahoy"
  [3]=>
  string(3) "qux"
  [4]=>
  string(4) "quux"
}  

Notice how the white-spaces used in the heredoc declaration did not make in to the var_dump()'d output, and we continued to add more element to the $foo array after the

$foo = ['foo', 'bar', <<<EOT
  baz
    -  hello world! --
  ahoy
  EOT, 'qux', 'quux'
];

var_dump($foo);
0 token

Backwards compatibility impact

As long as you don't have any heredox/nowdoc string literals that contain the same token as the first positive character in a line, you are golden

$foo = <<<HELLO
  HELLO_WORLD <-- this will not terminate the string literal
  HELLOWORLD <-- this one will not either. 
  HELLO WORLD<-- this one will
HELLO;

If you have any heredoc/nowdoc syntax similar to the above, note that with PHP 7. 3, PHP assumes the

$foo = ['foo', 'bar', <<<EOT
  baz
    -  hello world! --
  ahoy
  EOT, 'qux', 'quux'
];

var_dump($foo);
1 terminates the string literal, and will throw an error on the next line. In earlier versions, the
$foo = ['foo', 'bar', <<<EOT
  baz
    -  hello world! --
  ahoy
  EOT, 'qux', 'quux'
];

var_dump($foo);
2 is not considered the ending token of the heredoc. Thanks to /u/ImSuperObjective2 on reddit for pointing this out

In PHP, there are numerous ways to specify a string value. The two most frequent methods are using single or double quotations

Dấu ngoặc kép

With double quoted string, escape characters like \n, is regarded as a new line break and variables are replaced with their values. As in this example

1
2
3
4
5
6

$hello = 'Hello';
echo " $hello\n World. ";

// đầu ra
// Xin chào
// Thế giới

Dấu nháy đơn

When strings that are single quoted, they are treated as literal, meaning that escaped characters do not expand; for example, ‘\n’ will not create a new line. Variables are not replaced by the values assigned to them

1
2
3
4
5

$hello = 'Hello';
echo '$hello\nWorld. ';

// đầu ra
// $xin chào\nThế giới

When we wish to define a multiline string, things become messier. For example, on occasions, we need to include multi-line javascript in PHP such as

1
2
3
4

function foo ( status , rowid )
{
    $ ("#reportsTo") . attr("size", 10);
}

Introducing Heredoc and Nowdoc

Luckily, PHP offers a better way to write multiple-line string variables directly with and syntax

The basic rules for Heredoc and Nowdoc are

  • * Starting with a “triple less-sign” before a unique identifier for the beginning and end of the string,
  • * The delimiter must always be at the beginning of a line, without any spaces, letters, or other characters
  • * The closing identifier must be on a new line, followed by a semi-colon, and with no white space before it

Ví dụ

1
2
3
4
5
6
7
8
9
10
11
12
13

$size = 10;
echo <<
function foo(status, rowid)
{
    $("#reportsTo"). attr("size", $size);
}
EOT
;

// Đưa ra
// function foo(status, rowid)
// {
//  $("#reportsTo"). attr("kích thước", 10);
// }

We could use any string to represent identifier to mark the start and end of the string. The triple less sign must always come before the opening identifier

Heredoc differs from Nowdoc in that it makes use of double-quoted strings. For escape sequences, etc. , parsing is performed inside a heredoc, but a nowdoc employs single-quoted texts and hence parsing is not performed

1
2
3
4
5
6
7
8
9
10
11
12
13

$size = 10;
echo <<
function foo(status, rowid)
{
    $("#reportsTo"). attr("size", $size);
}
EOT
;

// Đầu ra
// function foo(status, rowid)
// {
//  $("#reportsTo"). attr("size", $size);
// }

Phần kết luận

Heredoc and nowdoc are handy alternatives to the more frequently used quoted string syntax in PHP for creating strings, especially string that spans multiple lines

So the next time when you dealing with a long string, try heredoc or nowdoc

bài viết liên quan

  • CRUD PHP Datagrid (Editable Datagrid) *

    * CRUD PHP Datagrid feature is only available in paid versions.   The PHP datagrid is…

  • set_databar() *

    * Please note this feature is not available in Lite and Basic versions. Thông số. $col_name. Tên…

  • set_col_datetime()

    * Currently only supported in the commercial licenses  The function is almost identical to set_col_date() except…

    Why use heredoc in PHP?

    Heredoc is one of the ways to store or print a block of text in PHP . The data stored in the heredoc variable is more readable and error-free than other variables for using indentation and newline.

    Should I use heredoc?

    Heredoc's are a great alternative to quoted strings because of increased readability and maintainability . You don't have to escape quotes and (good) IDEs or text editors will use the proper syntax highlighting.

    What is heredoc in PHP?

    Heredoc PHP syntax is a way to write large bloc of text inside PHP, without the classic single quote, double quotes delimiters . It relies on <<< and a token that will also mark the end of the string.

    What is Newdoc in PHP?

    Newdoc is similar to the heredoc, but in newdoc parsing is not done . It is also identified with three less than symbols <<< followed by an identifier. But here identifier is enclosed in single-quote, e. g. <<