我想知道,插入PHP变量到字符串的正确方法是什么? 这种方式:
echo "Welcome ".$name."!"
或者这样:
echo "Welcome $name!"
这两种方法都可以在我的PHP v5.3.5中使用。后者更短更简单,但我不确定前者是更好的格式还是更合适。
我想知道,插入PHP变量到字符串的正确方法是什么? 这种方式:
echo "Welcome ".$name."!"
或者这样:
echo "Welcome $name!"
这两种方法都可以在我的PHP v5.3.5中使用。后者更短更简单,但我不确定前者是更好的格式还是更合适。
当前回答
从php4开始,你可以使用字符串格式化器:
$num = 5;
$word = 'banana';
$format = 'can you say %d times the word %s';
echo sprintf($format, $num, $word);
来源:sprintf ()
其他回答
我一直都喜欢这种方式,而且发现它容易得多。
echo "Welcome {$name}!"
从简单、易读、一致和易于理解的角度来看(因为性能在这里并不重要):
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.
在某些特定情况下,“嵌入vars的双引号”可能是有用的,但一般来说,我会使用串联(方便时使用单引号或双引号)
我知道这是一个老问题,但我认为有人必须提到所有的优点和缺点:
这是个人偏好。
性能:没有区别。正如许多人提到的,如果使用不切实际的许多变量,双引号可能会更快。
更好的用法:单引号(大多数情况下)。正如@Khez所说,用单引号你可以连接任何东西,甚至是函数调用和变量修改,就像这样:echo 'hi '。(名字)美元。($i + 1);双引号能做而单引号不能做的唯一一件事是使用\n、\r、\t等。
可读性:没有区别(可能有个人偏好)。
可写性/可重写性/调试:在单行语句中没有区别,但在处理多行语句时,在调试或编写时注释/取消注释更容易。例如:
$q = 'SELECT ' .
't1.col1 ' .
',t2.col2 ' .
//',t3.col3 ' .
'FROM tbl1 AS t1 ' .
'LEFT JOIN tbl2 AS t2 ON t2.col2 = t1.col1 ' .
//'LEFT JOIN tbl3 AS t3 ON t3.col3 = t2.col2 ' .
'WHERE t1.col1 = ' . $x . ' ' .
' AND t2.col2 = ' . $y . ' ' .
//' AND t3.col3 = ' . $z . ' ' .
'ORDER BY t1.col1 ASC ' .
'LIMIT 10';
减少逃避:单引号。对于单引号,只需要转义2个字符('和\)。对于双引号,您需要转义2个字符(",\),如果需要,还需要转义3个字符($,{和})。
变化少:单引号。例如,如果你有以下代码:
echo 'Number ' . $i . '!';
你需要增加1到$i,所以它变成了like:
echo 'Number ' . ($i + 1) . '!';
但是对于双引号,你需要改变这个:
echo "Number $i!";
:
echo "Number " . ($i + 1) . "!";
结论:用你喜欢的。
从php4开始,你可以使用字符串格式化器:
$num = 5;
$word = 'banana';
$format = 'can you say %d times the word %s';
echo sprintf($format, $num, $word);
来源:sprintf ()
如果你想执行一个SQL命令,而你的变量是数组成员,那么你不应该在数组的[]中使用单引号(像这样:["]);例如,如果你使用这个字符串作为SQL命令,你会得到服务器错误500:
$con = mysqli_connect('ServerName', 'dbUsername', 'dbPassword');
mysqli_select_db($con, 'dbName')
//'ID' is auto increment field.
$sql = "INSERT INTO sampleTable (ID, TraceNo) VALUES ('','$sampleArray['TraceNo']')";
mysqli_query($con, $sql)
正确的字符串是:
//'ID' is auto increment field.
$sql = "INSERT INTO sampleTable (ID, TraceNo) VALUES ('','$sampleArray[TraceNo]')";