使用变量时字符串封装的方法[重复]

This question already has an answer here:

This may be a very basic question, but I have struggled to find a suitable answer. And my first question, so please be gentle.

When combining strings with variables, I understand that enclosing variables within a single-quoted string will not expand the variable, whereas double quoted strings will expand the variable (and other special characters), giving rise to the syntax in the two examples:

$animal1='brown fox';
$animal2='lazy dog';
echo "The quick $animal1 jumps over the $animal2";
echo 'The quick '.$animal1.' jumps over the '.$animal2;

I recall reading that PHP parses single quote encapsulated strings faster than double quoted encapsulated strings, because it is not spending time looking for variables that it needs to resolve. Is this true? If so, is this gain lost when concatenating a string and a variable, as in the second example?

My main question is: When working with strings and variables, as in the above examples, is either way of encapsulating preferable?

</div>

I recall reading that PHP parses single quote encapsulated strings faster than double quoted encapsulated strings, because it is not spending time looking for variables that it needs to resolve. Is this true?

No, this is wrong, see Disproving the Single Quotes Performance Myth (Jan 2012; By Nikic)

My main question is: When working with strings and variables, as in the above examples, is either way of encapsulating preferable?

That is only a matter of taste, find your way and don't get distracted by misguiding and false information you find online. Write the way you can read and edit it well.

Here's some benchmark that you can refer to:

http://www.phpbench.com/

Look for the single quotes vs double quotes part. The difference is so small that unless you're going to do it a zillion times, there's not going to be a performance impact at all.

There is one more way you can encapsulate variables, useful especially when you're working with arrays:

$str = "Encapsulating an array {$array['key']}";

It is very slightly faster to use ' instead of " in general. This difference is so small though in most PHP applications you would never notice the difference. In regards to the concatenation, both are about similar speeds, there is very little difference between them, read benchmarks here: https://stackoverflow.com/a/1813685/2859624

Although there is only minimal time difference (Something that e.g., is negligable compared to server-client communication times), one way makes for a much clearer text. The latter makes it A LOT easier for you to spot variables inserted into text.

I'd always take the variables out of regular text, as in example 2 you give.