【问题标题】:PHP - calling a constant from inside a string [duplicate]PHP - 从字符串中调用常量[重复]
【发布时间】:2011-05-14 03:49:47
【问题描述】:

可能重复:
Include constant in string without concatenating

我看到你可以像这样在字符串中调用调用变量:$X = "bla bla $variable"; 我也可以用常量来做这件事吗?如果可以的话,synthax 是什么?

【问题讨论】:

  • 谢谢你回答了我的问题。所以没有办法做到这一点
  • 我喜欢链接问题的答案......他们很有趣。

标签: php string variables


【解决方案1】:

是的。

$X = "bla bla" . CONSTANT_NAME;

【讨论】:

  • 但它并不是真的在字符串里面 :)
  • 嗯,有点像。我们使用字符串连接,但我猜你希望它在引号内。
【解决方案2】:

你不能在字符串中调用它,所以你必须输入$X = "bla bla " . constant

如果您真的想从字符串中调用它,那么您必须使用 get_defined_constants 函数:

$consts = get_defined_constants();
echo "bla bla {$consts['constant']}";

但实际上,没有意义;-)

【讨论】:

    【解决方案3】:

    默认情况下不可能这样做。可能可以编写一个函数来解析字符串,但你为什么要这样做:P

    【讨论】:

      【解决方案4】:

      还有命令插值技巧:

      $php = "htmlspecialchars";
      # or = function ($s) {return $s}
      
      $string = "bla bla {$php(constant('CNAME')} bla";
      $string = "but just {$php(CONSTANT_NAME)} should also work";
      

      【讨论】:

        猜你喜欢
        • 2018-02-04
        • 2023-03-09
        • 1970-01-01
        • 2013-07-19
        • 1970-01-01
        • 2016-04-23
        • 2015-06-21
        • 2012-12-13
        • 1970-01-01
        相关资源
        最近更新 更多