lyxal
lyxal

Reputation: 1118

Why Does String Interpolation Only Work In Double Quotes PHP

I've noticed through programming in PHP that string interpolation ("blah blah ${foo}") only works in double-quoted strings ("...").

For instance, this line will work:

$bar = "foo";
echo "I like ${bar}";

>> I like foo

But this one won't:

$bar = "foo";
echo 'I like ${bar}';

>> I like ${bar}

I understand that the PHP Manual talks about the fact that interpolation is only acted upon in such strings, but it doesn't explain why it was chosen to work in this way.

So that's my question --- why is it that string interpolation only works in double-quoted strings in PHP?

Upvotes: 0

Views: 2105

Answers (2)

lonesomeday
lonesomeday

Reputation: 237975

The obvious answer is that there are times when you might not want variables to be interpreted in your strings.

Take, for example, the following line of code:

$currency = "$USD";

This produces an "undefined variable" notice and $currency is an empty string. Definitely not what you want.

You could escape it ("\$USD"), but hey, that's a faff.

So PHP, as a design decision, chose to have double-quoted strings interpolated and single-quoted strings not.

Upvotes: 5

stateofgary
stateofgary

Reputation: 23

It works that way by definition. That's the way it was made to work. There is no 'why' other than that's the way the developers of PHP chose to implement the feature.

Upvotes: -4

Related Questions