简体   繁体   English

在 PHP 中,“<<<”代表什么?

[英]In PHP, what does "<<<" represent?

例如:

$sql = <<<MySQL_QUERY

That's heredoc syntax.这是heredoc 语法。 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.您可以通过将<<<加上您选择的标记来开始一个 heredoc 字符串,并通过在新行中仅放置标记(而不是其他任何东西!)来终止它。 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;

It is the start of a string that uses the HEREDOC syntax.它是使用HEREDOC 语法的字符串的开头。

A third way to delimit strings is the heredoc syntax: <<<.分隔字符串的第三种方法是heredoc 语法:<<<。

After this operator, an identifier is provided, then a newline.在这个运算符之后,提供了一个标识符,然后是一个换行符。 The string itself follows, and then the same identifier again to close the quotation.紧随其后的是字符串本身,然后再次使用相同的标识符来关闭引号。

This is called a heredoc , and it lets you do a long piece of text that goes over several lines.这称为heredoc ,它可以让您制作一段跨越多行的长文本。 You can put PHP variables in there and they will replace with the value.您可以将 PHP 变量放在那里,它们将替换为值。 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.您可以通过附加多个带引号的字符串来做同样的事情,但是对于像这样的 HTML 文本这样的扩展文档,这在大多数情况下更清晰。 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.还有一种叫做nowdoc 的东西,它类似于 PHP 中的单引号字符串,但它们不允许您在其中使用变量。

It's PHP's heredoc .这是 PHP 的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.这是一个heredoc,对于长字符串,你不必担心引号之类的。 If you notice the word CHART and then there's a line that says CHART;, that indicates the end of the string.如果您注意到CHART 这个词,然后有一行显示CHART;,表示字符串的结尾。

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.使用这种格式时要记住的重要一点是,无论您使用什么字符串来定义字符串的结尾(例如本例中的 CHART),该单词都必须单独出现在一行中,后跟一个分号,并且 NO字符可以出现在同一行的分号之后,甚至是空格,否则 PHP 认为它是字符串的一部分。

It's the heredoc syntax .这是heredoc 语法

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

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.结论:如果我们使用第一种方法,我们必须将其转换为json_encode() ,这需要一些处理。 Instead, We can use the <<< operator to save some time and get some clean code.相反,我们可以使用<<<运算符来节省一些时间并获得一些干净的代码。 :) :)

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.我发现HeredocNowdocPHP都非常强大和有用,我很惊讶到目前为止没有人给出更多关于你可以做什么的例子。

First the difference between Heredoc and Nowdoc is simple,首先HeredocNowdoc很简单,

  • Heredoc : Is like the "" double quote string you can put Variables Heredoc : 就像 "" 双引号字符串一样可以放变量
  • Nowdoc : Is like the '' single quote string no variable are parsed Nowdoc :就像 '' 单引号字符串一样,没有解析变量

For the following example I will only show the Heredoc , in order to make a Nowdoc just wrap the token inside single quotes -> 'TOKEN'.对于以下示例,我将仅显示Heredoc ,为了制作Nowdoc只需将标记包裹在单引号内 -> '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.轻松输出带有动态变量的HTML代码,避免usesell串联。
  • 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这些行是用 '\\n' 字面解释的,因此就像写在文档中一样,添加也很有用
    with nl2br .与 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使用 nl2br 为每一行添加<br>

This works because HEREDOC interpretes each \\n as an actual line这是有效的,因为 HEREDOC 将每个 \\n 解释为实际的行

   // 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或者只是放入一个字符串然后输出 1 个回声

    <?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文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM