When browsing a PHP documentation, an example at the bottom of the Complex (curly) syntax section explaining a usage of a scope resolution operator (::) within a curly syntax for strings in PHP caught my eye. Let's look at it:

// Show all errors.

class beers {
    const softdrink = 'rootbeer';
    public static $ale = 'ipa';

$rootbeer = 'A & W';
$ipa = 'Alexander Keith\'s';

// This works; outputs: I'd like an A & W
echo "I'd like an {${beers::softdrink}}\n";

// This works too; outputs: I'd like an Alexander Keith's
echo "I'd like an {${beers::$ale}}\n";

I started to think about the above code excerpt, but it was weird, as I did not expect to see A & W nor Alexander Keith in the outputs. For a brief moment I thought that maybe a documentation is wrong, so I decided to run the script. What I expected to see was:

I'd like an rootbeer
I'd like an ipa

To be fair, I was not so sure about the ipa from the second line, but I was pretty much sure the first line would should print rootbeer. For my surprise, my PHP 8.1 interpreter matched the comments from the script:

I'd like an A & W
I'd like an Alexander Keith's

To be honest, I have not have not been so confused about PHP in a good while. Before I run that script I thought for myself: Nice, I found a way to use a classname, or more importantly, self:: and static:: to print constants inside a string. Unfortunately, or maybe fortunately as I learned something new, the script had shown me that I do not understand what is happening.


There is a note in the documentation above the script, so for completeness I copied it over. It took me at least three re-reads to fully understand, so take your time in case you are also confused at this point:

The value accessed from functions, method calls, static class variables, and class constants inside {$} will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

In case it still does not make sense to you, the short answer sadly is: It is not possible. Maybe in future PHP releases. You simply have to use a string concatenation operator when referencing a content of a class constant. Or in other words, this is the only correct way to go:


class beers {
    const softdrink = 'rootbeer';

echo "I'd like an " . beers::softdrink . "\n";

On the other hand, you can now write some really hard-to-understand code the way it was written in the example script from the beginning of the post and cause some serious headache to your colleagues (or your future self for that matter). I was joking. Don't do it. Write code that is easy-to-understand whenever possible! Enjoy.