双引号中的 PHP 静态属性
如何让 PHP 计算双引号中的静态变量?
我想做这样的事情:
log("self::$CLASS $METHOD entering");
我尝试了各种 {}
组合来获取 self::$CLASS
的变量值,但没有任何效果。 我目前已经解决了字符串连接问题,但输入起来很痛苦:
log(self::$CLASS . " $METHOD entering");
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");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
抱歉,你不能这样做。 它仅适用于简单的表达式。 请参阅此处。
Sorry, you can't do that. It only works for simple expressions. See here.
不幸的是,目前还没有办法做到这一点。 这里的答案之一的示例将不起作用,因为
{${self::$CLASS}}
不会返回self::$CLASS
的内容,但会返回内容名称为self::$CLASS
的变量。下面是一个示例,它不返回
myvar
,而是返回aaa
: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
:使用存储在变量中的匿名标识函数。 这样,您将在
{
: 之后立即看到$
:(我在本示例中使用类常量,但这也适用于静态变量)。
Use an anonymous identity function stored in a variable. This way you will have
$
immediately after{
:(I am using class constants in this example but this will work with static variables too).
我完成此任务的方法是为静态类本身设置一个变量:
然后我可以对其进行插值:
The way I've accomplished it is by setting a variable to the static class itself:
Then I can interpolate it:
8.2.14 - 8.2.17、8.3.0 - 8.3.4 的输出:
8.1.0 - 8.1.27(及更早版本)的输出
Output for 8.2.14 - 8.2.17, 8.3.0 - 8.3.4:
Output for 8.1.0 - 8.1.27 (and older)
我觉得奇怪的是没有人建议
sprintf
功能还没有。说:
你会使用它:
所以在你的例子中它是:
I find it odd that noone has suggested the
sprintf
function yet.say:
you would use it with:
so on your example its:
是的,可以这样做:
Yes this can be done: