开发者

Concatenation Operator

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


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.


In some cases your write less with:

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

VS

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜