Concatenation Operator

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

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



        
相关标签:
4条回答
  • 2021-01-22 14:30

    a. Yes. PHP has to parse the string for variables.

    b. Because of lines like: echo 'Your Ip address is' . get_ip() . '.';

    For reasons A and B.

    0 讨论(0)
  • 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."

    0 讨论(0)
  • 2021-01-22 14:53

    Addressing your last question:

    Every language has multiple was of doing the same thing. Flexibility is important in every language since any given method may be better the another from situation to situation. The only thing that you should worry about in regards to this is to be consistent in your own code.

    0 讨论(0)
  • 2021-01-22 14:56

    In some cases your write less with:

    $someLongVarName ="Hi";
    $someLongVarName .=" there";
    

    VS

    $someLongVarName ="Hi";
    $someLongVarName = "$someLongVarName there";
    
    0 讨论(0)
提交回复
热议问题