PHP - concatenate or directly insert variables in string

前端 未结 14 2597
無奈伤痛
無奈伤痛 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:13

    From the point of view of making thinks simple, readable, consistent and easy to understand (since performance doesn't matter here):

    • Using embedded vars in double quotes can lead to complex and confusing situations when you want to embed object properties, multidimentional arrays etc. That is, generally when reading embedded vars, you cannot be instantly 100% sure of the final behavior of what you are reading.

    • You frequently need add crutches such as {} and \, which IMO adds confusion and makes concatenation readability nearly equivalent, if not better.

    • As soon as you need to wrap a function call around the var, for example htmlspecialchars($var), you have to switch to concatenation.

    • AFAIK, you cannot embed constants.

    In some specific cases, "double quotes with vars embedding" can be useful, but generally speaking, I would go for concatenation (using single or double quotes when convenient)

提交回复
热议问题