PHP - concatenate or directly insert variables in string

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

    I prefer this all the time and found it much easier.

    echo "Welcome {$name}!"
    
    0 讨论(0)
  • 2020-11-22 05:37

    Go with the first and use single quotes!

    1. It's easier to read, meaning other programmers will know what's happening
    2. It works slightly faster, the way opcodes are created when PHP dissects your source code, it's basically gonna do that anyway, so give it a helping hand!
    3. If you also use single quotes instead of double quotes you'll boost your performance even more.

    The only situations when you should use double quotes, is when you need \r, \n, \t! The overhead is just not worth it to use it in any other case.

    You should also check PHP variable concatenation, phpbench.com for some benchmarks on different methods of doing things.

    0 讨论(0)
提交回复
热议问题