How can I get PHP to evaluate a static variable in double quotes?
I want to do something like this:
log("self::$CLASS $METHOD entering");
I've tried all sorts of {} combos to get the variable value of self::$CLASS, but nothing has worked. I've currently settled with string concatenation but it is a pain to type:
log(self::$CLASS . " $METHOD entering");
Just live with the concatenation. You'd be surprised how inefficient variable interpolation in strings can be.
And while this could fall under the umbrella of pre-optimization or micro-optimization, I just don't think you actually gain any elegance in this example.
Personally, if I'm gonna make a tiny optimization of one or the other, and my choices are "faster" and "easier to type" - I'm gonna choose "faster". Because you only type it a few times, but it's probably going to execute thousands of times.
Use an anonymous identity function stored in a variable. This way you will have
$
immediately after{
:$I = function($v) { return $v; }; $interpolated = "Doing {$I(self::FOO)} with {$I(self::BAR)}";
(I am using class constants in this example but this will work with static variables too).
Unfortunately there is no way how to do this yet. Example in one of answers here will not work, because
{${self::$CLASS}}
will not returns content ofself::$CLASS
, but will returns content of variable with name inself::$CLASS
.Here is an example, which does not returns
myvar
, butaaa
:Sorry, you can't do that. It only works for simple expressions. See here.
I know this is an old question but I find it odd that noone has suggested the
[sprintf][1]
function yet.say:
you would use it with:
so on your example its:
Yes this can be done: