我正在从Head First PHP和MySQL一起学习PHP和MySQL ,在书中,他们经常拆分他们的长字符串(超过80个字符)并连接它们,如下所示:
$variable = "a very long string " .
"that requires a new line " .
"and apparently needs to be concatenated.";
Run Code Online (Sandbox Code Playgroud)
我对此没有任何问题,但令我感到奇怪的是,其他语言的空格通常不需要连接.
$variable = "you guys probably already know
that this simply works too.";
Run Code Online (Sandbox Code Playgroud)
我试过这个,它工作得很好.换行总是用空格解释吗?如果它们跨越一行,甚至PHP手册也不会在echo示例中连接.
我应该遵循我的书的例子还是什么?我无法分辨哪个更正确或"正确",因为工作和手册甚至采用更短的方法.我还想知道将代码宽度保持在80个字符以下有多重要?因为我的显示器非常大而且我讨厌当我有屏幕空间时我的代码被缩短了,所以我一直很好用单词扭曲.
在PHP中构建多行字符串有3种基本方法.
一个.通过连接和嵌入的换行构建字符串:
$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..."`
Run Code Online (Sandbox Code Playgroud)
湾 多行字符串赋值,带有嵌入的换行符:
$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";
Run Code Online (Sandbox Code Playgroud)
C.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;
Run Code Online (Sandbox Code Playgroud)
Heredocs通常优选用于构建多线串.您不必在文本中转义引号,变量在它们内插,就好像它是一个常规的双引号字符串,并且文本中的换行符合.
| 归档时间: |
|
| 查看次数: |
11780 次 |
| 最近记录: |