我想知道,插入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 ()

其他回答

从第一个开始,使用单引号!

它更容易阅读,这意味着其他程序员将知道发生了什么 它的工作速度略快,PHP解剖源代码时创建操作码的方式,基本上都会这样做,所以给它一个帮助! 如果你也使用单引号而不是双引号,你会进一步提高你的表现。

只有当你需要\r, \n, \t时,你才应该使用双引号! 在任何其他情况下使用它的开销都是不值得的。

您还应该检查PHP变量拼接,phpbench.com,以获得关于不同操作方法的一些基准测试。

两种都可以。使用对你来说能见度更好的那个。说到可见性,你也可以查看printf。

如果你想执行一个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]')";

不要连接。这是不需要的,我们的逗号作为echo可以接受多个参数

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的双引号”可能是有用的,但一般来说,我会使用串联(方便时使用单引号或双引号)