Concatenation Operator

[亡魂溺海] 提交于 2019-12-20 03:31:24

问题


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

<?php
  $x="Hi";
  $y=" There";
  $z = $x.$y;
  $a = "$x$y";
  echo "$z"."<br />"."$a";
?>

$z uses the traditional concatenation operator provided by php and concatenates, conversely $a doesn't,

My questions:

  1. by not using the concatenation operator, does it effect the performance?

  2. If it doesn't why at all have the concatenation operator.

  3. Why have 2 modes of implementation when one does the work?


回答1:


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




回答2:


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.




回答3:


In some cases your write less with:

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

VS

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



回答4:


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.



来源:https://stackoverflow.com/questions/3041906/concatenation-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!