Yesterday on Twitter there was a conversation started by Marco Pivetta regarding a particularly horrible bit of code he had spotted:
What the actual f***?
— Horizontally scalable (@Ocramius) July 7, 2015
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.
— auroraeosrose (@auroraeosrose) July 7, 2015
I then added this to the conversation:
— Davey Shafik 🦁🐉🏳️🌈 (@dshafik) July 7, 2015
— Trevor Suarez (@trevorsuarez) July 7, 2015
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']::BAR, really? But it’s interesting to see just how consistent, and flexible the new Uniform Variable Syntax is.
$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.