代码之家  ›  专栏  ›  技术社区  ›  Tarik

在PHP中:如果我在源代码中编写字符串时开始一个新行,是否需要连接该字符串?

php
  •  2
  • Tarik  · 技术社区  · 16 年前

    我正在一起学习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

    我应该以我的书为榜样吗?我分不清哪一个更正确,哪一个更“合适”,因为工作和手册都采用了更短的方法。我也想知道它有多重要,保持代码在80个字符以下的宽度?我一直对wordwarp很好,因为我的显示器相当大,我讨厌我的代码在屏幕空间被剪短。

    5 回复  |  直到 16 年前
        1
  •  5
  •   Marc B    16 年前

    在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..."`
    

    b。带嵌入换行符的多行字符串赋值:

    $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;
    

        2
  •  1
  •   AlexV    16 年前

    在PHP中,长字符串不需要串联,但请记住:

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

    相当于

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

    所以要回答你的问题,不,你不必把大的弦折成许多小的弦。这样做只是一个偏好的问题(我并不经常看到)。

        3
  •  0
  •   Zak    16 年前

    80个字符的“限制”可以追溯到以前,终端屏幕的宽度是80个字符。如果您需要在窄宽度终端中编辑某些内容,那么使用80个字符是很有帮助的。但是,如果超过80个字符行的包装在编辑器中引起了麻烦,请不要遵循这种惯例。

    当您有第二个示例中的多行字符串时,该字符串将与您在编辑器中键入的字符串完全相同。如果在retrun char之前有一大堆空格,那么这些空格将出现在string var中。唯一的例外是,如果编辑器正在换行,那么字符串中实际上没有返回字符,并且它不会出现在变量中。

        4
  •  0
  •   Álvaro González    16 年前

    PHP语法允许字符串中的文本换行。你的第二个例子是:

    you guys probably already know[LF][SPACE][SPACE][SPACE][SPACE]that this simply works too.

    你会在哪里 \r\n \n 取决于编辑器设置。那些多余的空间可能是个问题(不是所有的东西都是HTML),但这和连接不一样。

        5
  •  0
  •   BDuelz    16 年前

    不。

    1) open quotes
    2) write as much as you need, adding spaces, tabs, whatever else
    3) close quotes.
    

    如果在中使用相同的引号,请使用\

    "Jane said \"It's hot today!\"";
    

    'Jane said "It\'s hot today!"';
    
    推荐文章