PHP - concatenate or directly insert variables in string

前端 未结 14 2397
無奈伤痛
無奈伤痛 2020-11-22 04:45

I am wondering, What is the proper way for inserting PHP variables into a string?

This way:

echo \"Welcome \".$name.\"!\"
         


        
14条回答
  •  盖世英雄少女心
    2020-11-22 05:21

    Between those two syntaxes, you should really choose the one you prefer :-)

    Personally, I would go with your second solution in such a case (Variable interpolation), which I find easier to both write and read.

    The result will be the same; and even if there are performance implications, those won't matter 1.


    As a sidenote, so my answer is a bit more complete: the day you'll want to do something like this:

    echo "Welcome $names!";
    

    PHP will interpret your code as if you were trying to use the $names variable -- which doesn't exist. - note that it will only work if you use "" not '' for your string.

    That day, you'll need to use {}:

    echo "Welcome {$name}s!"
    

    No need to fallback to concatenations.


    Also note that your first syntax:

    echo "Welcome ".$name."!";
    

    Could probably be optimized, avoiding concatenations, using:

    echo "Welcome ", $name, "!";
    

    (But, as I said earlier, this doesn't matter much...)


    1 - Unless you are doing hundreds of thousands of concatenations vs interpolations -- and it's probably not quite the case.

提交回复
热议问题