Heredoc vs nowdoc php

Heredoc and Nowdoc 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 = <<

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
    $foo = ['foo', 'bar', <<
    0
  6. You can add more expressions after the ending token without any errors
$foo = ['foo', 'bar', <<

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

$foo = ['foo', 'bar', <<
1'd output, and we continued to add more element to the
$foo = ['foo', 'bar', <<
2 array after the
$foo = ['foo', 'bar', <<
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 = <<

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

$foo = ['foo', 'bar', <<
1 terminates the string literal, and will throw an error on the next line. In earlier versions, the
$foo = ['foo', 'bar', <<
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. ";

// output
// Hello
// World.

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. ';

// output
// $hello\nWorld

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 Heredoc and Nowdoc 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
;

// Out put
// function foo(status, rowid)
// {
//  $("#reportsTo"). attr("size", 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
;

// Output.
// 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…

    What is Nowdoc in PHP?

    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.

    What is a heredoc 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.

    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 need for heredoc in PHP?

    The heredoc syntax is a way to declare a string variable . The heredoc syntax takes at least three lines of your code and uses the special character <<< at the beginning.