简体   繁体   中英

Whats better when echoing strings

Im just curious as to what is the difference to these 3 types of strings.

echo "Hello my name is ".$name;

echo "Hello my name is $name";

echo "Hello my name is {$name}";

I know that in the third case its required over the 2nd when your using arrays with keys. For example, i know the following wont work.

echo "Hello my name is $data['name']";

You would need to do...

echo "Hello my name is{$data['name']}";

for it to work.

Does anyone have an explanation as to why this is?

"$foo""{$foo}"之间的区别仅是解析问题-内插时,PHP解析器仅解析某些字符以获取变量名, 除非它周围有{} (在这种情况下将解析任何字符) 。

Well it is opinion of each person. I like

echo "Hello my name is $name";

echo "Hello my name is ".$data['name'];

echo "Hello my name is $data['name']";
You would need to do...
echo "Hello my name is{$data['name']}";

you can do

echo "Hello my name is $data[name]";

I am strongly against concatenation, when simple variable interpolation in a string would suffice. Too much concatenation makes code unreadable.

"text $variable text"

for simple variables

"text {$array['key']} text"

for complex variables

People are giving their opinion, it's fine, but here are facts :

  • Concatenation is faster
  • The time gained by concatenating is trivial and not a good argument to justify its use
  • In the end, the code does the same thing whatever method you choose

Basically, it does not matter how you do it, just choose your favorite and stick with it. If you work with a group of people, just use the same convention, for clean code's sakes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM