gpt4 book ai didi

php - 在 PHP : If I start a new line while writing a string in my source is it necessary to concatenate the string?

转载 作者:行者123 更新时间:2023-12-03 23:08:27 25 4
gpt4 key购买 nike

我正在从 Head First PHP & MySQL 一起学习 PHP 和 MySQL,在书中,它们经常拆分长字符串(超过 80~ 个字符)并连接它们,如下所示:

$variable = "a very long string " .
"that requires a new line " .
"and apparently needs to be concatenated.";

我对此没有意见,但令我感到奇怪的是其他语言中的空格通常不需要连接。

$variable = "you guys probably already know
that this simply works too.";

我试过了,效果很好。换行符不是总是在末尾用空格解释吗?即使是 PHP manual如果它们跨越一行,则不会在 echo 示例中连接。

我应该按照书中的例子还是怎样?我不知道哪个更正确或“合适”,因为工作和手册甚至都采用了更短的方法。我还想知道将代码宽度控制在 80 个字符以下有多重要?由于我的显示器非常大,而且我讨厌我的代码在有屏幕空间时被缩短,所以我一直都很好地处理文字扭曲。

最佳答案

有 3 种在 PHP 中构建多行字符串的基本方法。

一个。通过连接和嵌入换行符构建字符串:

$str = "this is the first line, with a line break\n";
$str .= "this is the second line, but won't have a break";
$str .= "this would've been the 3rd line, but since there's no line break in the previous line..."`

多行字符串赋值,嵌入换行符:

$str = "this is the first line, with a line break\n
this is the second line, because of the line break.
this line will actually is actually part of the second line, because of no newline";

HEREDOC语法:

$str = <<<EOL
this is the first line
this is the second line, note the lack of a newline
this is the third line\n
this is actually the fifth line, because the newline previously isn't necessary.
EOL;

Heredocs 通常更适合构建多行字符串。您不必在文本中转义引号,变量在其中插入,就好像它是一个普通的双引号字符串一样,并且文本中的换行符被接受。

关于php - 在 PHP : If I start a new line while writing a string in my source is it necessary to concatenate the string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3197577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com