In PHP, you can embed a variable into a string in these two ways:

$a = 'b';
echo "1: $a"; // outputs "1: b"
echo "2: {$a}"; // outputs "2: b"

However, you can also embed it in this arguably-more-confusing way:

echo "3: ${a}"; // outputs "3: b", but why!?

And, moreover:

$b = 'c';
echo "4: ${$a}"; // outputs "4: c". This is insanity.

For the third case, I guess the logic is that whatever is inside the braces is interpreted as an expression and, in PHP, when using an undefined constant (in this case, a), the parser translates it to a string ("a"), making ${a} the same as $a. However, you normally get a warning when this conversion happens, which doesn't show for us:

php > echo hello;
PHP Warning:  Use of undefined constant hello - assumed 'hello' (this will throw an Error in a future version of PHP) in php shell code on line 1

Luckily, these two cases are being deprecated and going away in PHP 9.

Final thoughts

It's nice to see PHP slowly get better as a language. It's already unrecognizable from its earlier versions.

Previous on PHP
Mastodon Mastodon