最佳实践:在PHP中使用长的多行字符串吗? [英] Best Practices: working with long, multiline strings in PHP?

查看:67
本文介绍了最佳实践:在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;
    }
}

但它也可以写为:

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

但是换行和回车有什么用呢?有什么不同? \n\n是否等于\r\r\n\r?在行与行之间创建行距时应该使用哪个?

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

然后有输出缓冲和heredoc语法的选项.

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

如何处理在对象中使用长的多行字符串?

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

推荐答案

您应使用HEREDOC或NOWDOC.

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;

Heredoc与Nowdoc的区别在于,将执行执行Heredoc中嵌入的PHP代码,而将按原样打印出Nowdoc中的PHP代码.

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;

在这种情况下,$ text的值将为My $var.

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

注意:在结束EOT;之前应该没有空格或制表符.否则你会得到一个错误

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

这篇关于最佳实践:在PHP中使用长的多行字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆