开发者

In PHP, what does "<<<" represent?

For example:

$sql = <<<MySQL_开发者_如何转开发QUERY


That's heredoc syntax. You start a heredoc string by putting <<< plus a token of your choice, and terminate it by putting only the token (and nothing else!) on a new line. As a convenience, there is one exception: you are allowed to add a single semicolon after the end delimiter.

Example:

echo <<<HEREDOC
This is a heredoc string.

Newlines and everything else is preserved.
HEREDOC;


This is called a heredoc, and it lets you do a long piece of text that goes over several lines. You can put PHP variables in there and they will replace with the value. The word CHART can be anything. It just needs to be the same to start and stop where the quoted text begins.

You could do the same thing by appending multiple quoted strings, but this is cleaner most of the time for extended documents like this HTML text. There is also something called a nowdoc which is like a single quote string in PHP, but these won't let you use variables inside them.


It is the start of a string that uses the HEREDOC syntax.

A third way to delimit strings is the heredoc syntax: <<<.

After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.


It's PHP's heredoc.

Example:

$sql = <<<MySQL_QUERY
SELECT * 
FROM TAB 
WHERE A = 1 AND B = 2 
MySQL_QUERY;           


It's a heredoc, for long strings that you don't have to worry about quotation marks and whatnot. If you notice the word CHART and then there's a line that says CHART;, that indicates the end of the string.

The important thing to remember when using this format is that whatever string you use to define the end of the string (such as CHART in this case), that word has to appear on a line on its own, followed by a semicolon, and NO characters can occur after the semicolon on the same line, even whitespace, otherwise PHP thinks it's part of the string.


It's the heredoc syntax.

$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;


I found both Heredoc and Nowdoc extremelly powerfull and usefull in PHP and I am surprise that no one have so far give more example of what you can do.

First the difference between Heredoc and Nowdoc is simple,

  • Heredoc: Is like the "" double quote string you can put Variables
  • Nowdoc: Is like the '' single quote string no variable are parsed

For the following example I will only show the Heredoc, in order to make a Nowdoc just wrap the token inside single quotes -> 'TOKEN'.

Features and Advantages

  • The "" and '' can be added as much as needed and won't cause any errror
  • Easily output HTML code with dynamic variables, avoid usesell concatenations.
  • Store it in variables for letter use, can create small components and just output them.
  • The Lines are interpreted literally with '\n' hence is like writing in a doc, also useful to add
    with nl2br .

Simple Example

$a = "Hello";
$b = "World";
// HEREDOC
echo <<<HEREDOC
<strong> HEREDOC:  </strong> 
Variable A: "$a" 
Variable B: "$b"
HEREDOC;
echo '</br>';

// NOWDOC
echo <<<'NOWDOC'
<strong> NOWDOC:  </strong> 
Variable A: "$a" 
Variable B: "$b"
NOWDOC;

output

HEREDOC: Variable A: "Hello" Variable B: "World"
NOWDOC: Variable A: "$a" Variable B: "$b"

Recipes

  1. Use nl2br to add <br> for each line

This works because HEREDOC interpretes each \n as an actual line

   // HEREDOC
    echo nl2br(<<<HEREDOC
    <strong> HEREDOC:  </strong> 
    Variable A: "$a" 
    Variable B: "$b"
    HEREDOC);
    // Output HEREDOC:
    //Variable A: "Hello"
    //Variable B: "World"
  1. Create small components

         <?php
             foreach($tasks  as $task) {
                 // Create an HTML like component
                 $component = <<<HEREDOC
                 <div class="pure-u-1-3">
                     <div class="card">
                         <div class="card-header">
                            {$task['name']}
                         </div>
                         <div class="card-body">
                             <h5 class="card-title"> {$task['state']} </h5>
                             <p class="card-text"> {$task['description']} </p>
                             <a href="view?model=todo_list&task_id={$task['id']}" class="btn btn-primary">See Task Todos</a>
                         </div>
                     </div>                    
                 </div>
                 HEREDOC;
                 echo $component; // Output
    
             }
    
         ?>
    

Or just put in one string then output with 1 echo

    <?php
        $taskRendered = '';
        foreach($tasks  as $task) {
            // Create an HTML like component
            $component = <<<HEREDOC
            <div class="pure-u-1-3">
                <div class="card">
                    <div class="card-header">
                       {$task['name']}
                    </div>
                    <div class="card-body">
                        <h5 class="card-title"> {$task['state']} </h5>
                        <p class="card-text"> {$task['description']} </p>
                        <a href="view?model=todo_list&task_id={$task['id']}" class="btn btn-primary">See Task Todos</a>
                    </div>
                </div>                    
            </div>
            HEREDOC;
            $taskRendered .= $component;
        }
        echo $taskRendered; // Output
    
    ?>

Documentation

  • HEREDOC DOCS
  • NOWDOW DOCS


To get a clear idea:

$data = array(
  "Id" => 12345,
  "Cutomer" => "hi",
  "Quantity" => 2,
  "Price" => 45
);

curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));

If we use <<<:

$data = <<<DATA
{
  "Id": 12345,
  "Customer": "John Smith",
  "Quantity": 1,
  "Price": 10.00
}
DATA;

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

Conclusion: If we go with the 1st method we have to convert it into json_encode() which somehow requires some processing. Instead, We can use the <<< operator to save some time and get some clean code. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜