Concatenation Operator

后端 未结 4 1402
自闭症患者
自闭症患者 2021-01-22 14:07

This might be a silly question but it struck me, and here i ask.



        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-22 14:44

    1. Only slightly, since PHP has to parse the entire string looking for variables, while with concatenation, it just slaps the two variables together. So there's a tiny performance hit, but it's not noticeable for most things.

    2. It's a lot easier to concatenate variables like $_SERVER['DOCUMENT_ROOT'] using the concatenation operator (with quotes, you have to surround the variable in brackets or remove the single quotes in the array index; plus it just makes the string look all ugly). Plus, the concatenation operator allows more flexibility for formatting. For example, you can break up a long string literal onto multiple lines and then concatenate the different parts of it:

      $blah = "This is a really really long string. I don't even know how " .
          "long it is, but it's really long. Like, longer than an eel " .
          "or even a boa constrictor. Wow.";
      

      You can also use the concatenation operator to directly include return values from functions in a string literal (you can't include a function call in a double-quoted string), like this:

      $blah = "This has a " . fn_call() . " result, which can't go in the quotes.";
      
    3. I'm not sure I entirely understand what you're asking here, but I can say that PHP borrows a lot of things from Perl, and one of Perl's mantras is "There's more than one way to do it."

提交回复
热议问题