views:

279

answers:

3

Hi,

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");
+2  A: 

I don’t know the answer to your question, but you can show the class name and method using the __METHOD__ magic constant.

Nate
Thanks. This was helpful. I'm moving over from Java and haven't had a chance to dig into the magic constants. I'll use these instead of defining class and method variables.
Chris
A: 

Sorry, you can't do that. It only works for simple expressions. See here.

Electro
"Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {."If I understand this correctly, " {self::$METHOD} " won't work because the $ character must directly follow the left curly brace.
Chris
+1  A: 

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.

Peter Bailey