PHP - concatenate or directly insert variables in string

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

    Double-quoted strings are more elegant because you don't have to break up your string every time you need to insert a variable (like you must do with single-quoted strings).

    However, if you need to insert the return value of a function, this cannot be inserted into a double-quoted string--even if you surround it with braces!

    //syntax error!!
    //$s = "Hello {trim($world)}!"
    
    //the only option
    $s = "Hello " . trim($world) . "!";
    

提交回复
热议问题