dongtiao6362 2009-12-04 18:52
浏览 88
已采纳

最佳实践:使用PHP中的长多行字符串?

Note: I'm sorry if this is an extremely simple question but I'm somewhat obsessive compulsive over the formatting of my code.

I have a class that has a function that returns a string that will make up the body text of an email. I want this text formatted so it looks right in the email, but also so it doesn't make my code look funky. Here's what I mean:

class Something
{
    public function getEmailText($vars)
    {
        $text = 'Hello ' . $vars->name . ",

The second line starts two lines below.

I also don't want any spaces before the new line, so it's butted up against the left side of the screen.";
        return $text;
    }
}

but it could also be written as:

public function getEmailText($vars)
{
    $text = "Hello {$vars->name},
The second line starts two lines below.
I also don't want any spaces before the new line, so it's butted up against the left side of the screen.";
    return $text;
}

but what's the deal with new lines and carriage returns? What's the difference? Is the equivalent of or ? Which should I use when I'm creating a line gap between lines?

Then there's the option of output buffering and heredoc syntax.

How do you deal with using long multiline strings in your objects?

  • 写回答

10条回答 默认 最新

  • dongwuwu6104 2009-12-04 18:57
    关注

    You should use HEREDOC or NOWDOC.

    $var = "some text";
    $text = <<<EOT
      Place your text between the EOT. It's
      the delimiter that ends the text
      of your multiline string.
      $var
    EOT;
    

    The difference between Heredoc and Nowdoc is that PHP code embedded in a heredoc gets executed, while PHP code in Nowdoc will be printed out as is.

    $var = "foo";
    $text = <<<'EOT'
      My $var
    EOT;
    

    In this case $text will have the value My $var.

    Note: before the closing EOT; there should be no spaces or tabs. otherwise you will get an error

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(9条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度