注意:如果这是一个非常简单的问题,我很抱歉,但我对我的代码格式有点强迫症。
我有一个类,它有一个函数,该函数返回一个字符串,该字符串将构成电子邮件的正文。我希望此文本格式化,使其在电子邮件中看起来正确,但也不会使我的代码看起来很时髦。这就是我的意思:
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\ror \n\r?_ 当我在线条之间创建线条间隙时应该使用哪个?
\n\n
\r\r
\n\r
然后是输出缓冲和heredoc语法的选项。
你如何处理在你的对象中使用长的多行字符串?
您应该使用heredoc或nowdoc。
heredoc
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嵌入在 a 中的 PHP 代码heredoc被执行,而在其中的 PHP 代码nowdoc将按原样打印出来。
$var = "foo"; $text = <<<'EOT' My $var EOT;
在这种情况下$text会有值"My $var",不会"My foo"。
$text
"My $var"
"My foo"
笔记:
EOT;
EOT
<<<FOO
FOO;