PHP static variables in double quotes

*爱你&永不变心* 提交于 2019-11-27 02:07:44

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

micropro.cz

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 of self::$CLASS, but will returns content of variable with name in self::$CLASS.

Here is an example, which does not returns myvar, but aaa:

$myvar = 'aaa';
self::$CLASS = 'myvar';
echo "{${self::$CLASS}}";

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

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).

Peter Bailey

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.

I know this is an old question but I find it odd that noone has suggested the [sprintf][1] function yet.

say:

<?php

class Foo {

    public static $a = 'apple';

}

you would use it with:

echo sprintf( '$a value is %s', Foo::$a );

so on your example its:

log(
    sprintf ( ' %s $METHOD entering', self::$CLASS )
);
isaax2

Yes this can be done:

log("{${self::$CLASS}} $METHOD entering");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!