Class constants, how do they work? (Or: You Learn Something New Every Day…)

Yesterday on Twitter there was a conversation started by Marco Pivetta regarding a particularly horrible bit of code he had spotted:

If it’s unclear, this creates a string using sprintf() by prefixing ::PARAMNAME with the result of calling get_class() on the $api variable, and then passes that string into constant() which will give you the value of a constant using it’s string name.

At which point Elizabeth Smith chimed in to point out that $api::PARAMNAME would not work in older versions of PHP, necessitating this horrible workaround.

I then added this to the conversation:

Turns out, I was wrong. Whoops. Trevor Suarez created a past on showing that this did indeed work, going back to PHP 5.3 even.

Additionally, with PHP 7 — thanks to Uniform Variable Syntax — there are many more ways to achieve this too, as you can see below:

Now, obviously, a lot of these are facetious, I mean, who is going to do ['Foo'][0]::BAR, really? But it’s interesting to see just how consistent, and flexible the new Uniform Variable Syntax is.

The someFunction()::CONSTANT, SomeClass::method()::CONSTANT, and $obj->method()::CONSTANT are much more realistic, and likely to be something you will use at some point.

There were a few syntaxes that didn’t work, which on the one hand, I’m grateful for, but on the other, I think at least some of them should be possible. Presented without further comment:

As with everything in any programming language however:

just because you can do something, doesn’t mean you should

Use with caution.

Warning: file_get_contents(index.php): failed to open stream: No such file or directory in /nfs/c03/h02/mnt/170398/domains/ on line 441