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条)

报告相同问题?

悬赏问题

  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动