PHP-连接或直接在字符串中插入变量 [英] PHP - concatenate or directly insert variables in string

查看:653
本文介绍了PHP-连接或直接在字符串中插入变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,将PHP变量插入字符串的正确方法是什么?

这种方式:

I am wondering, What is the proper way for inserting PHP variables into a string?

This way:

echo "Welcome ".$name."!"

或者这样:

echo "Welcome $name!"

这两种方法都可以在我的PHP v5.3.5中使用.后者更短,更简单,但是我不确定第一种格式是否更好或是否被认为更合适.

Both of these methods work in my PHP v5.3.5. The latter is shorter and simpler but I'm not sure if the first is better formatting or accepted as more proper.

推荐答案

在这两种语法之间,您应该真正选择一个自己喜欢的语法:-)

Between those two syntaxes, you should really choose the one you prefer :-)

个人而言,在这种情况下(可变插值),我会考虑您的第二种解决方案,我发现它更容易读写.

Personally, I would go with your second solution in such a case (Variable interpolation), which I find easier to both write and read.

结果将是相同的;即使有性能影响,也没关系 1 .

The result will be the same; and even if there are performance implications, those won't matter 1.


作为旁注,所以我的回答更加完整:那天您要做这样的事情:


As a sidenote, so my answer is a bit more complete: the day you'll want to do something like this:

echo "Welcome $names!";

PHP将解释您的代码,就像您尝试使用$names变量一样-该变量不存在. -请注意,仅当您在字符串中使用"而不是"时,它才有效.

PHP will interpret your code as if you were trying to use the $names variable -- which doesn't exist. - note that it will only work if you use "" not '' for your string.

那天,您需要使用{}:

echo "Welcome {$name}s!"

无需回退到串联.


另请注意,您的第一个语法:


Also note that your first syntax:

echo "Welcome ".$name."!";

可以使用以下方法进行优化,避免级联:

Could probably be optimized, avoiding concatenations, using:

echo "Welcome ", $name, "!";

(但是,正如我之前说的,这没关系...)


1-除非您要进行数十万个级联与插值运算-情况可能并非如此.

这篇关于PHP-连接或直接在字符串中插入变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆