开发者

PHP - calling a constant from inside a string [duplicate]

开发者 https://www.devze.com 2023-01-26 15:58 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Include constant in string without concatenating
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Include constant in string without concatenating

Hi

I saw you can call call variables inside strings like this: $X = "bla bla $variable"; Can I also do t开发者_运维百科his with constants, and if I can, what's the synthax?


You can't call it inside strings, so you have to type $X = "bla bla " . constant.

If you really really wanted to call it from inside a string, then you'd have to use the get_defined_constants function :

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

But really, there's no point ;-)


Not possible to do that by default. It might be possible to write a function to parse the string, but why would you want to do that :P


Yes.

$X = "bla bla" . CONSTANT_NAME;


There is also the command interpolation trick:

$php = "htmlspecialchars";
# or = function ($s) {return $s}

$string = "bla bla {$php(constant('CNAME')} bla";
$string = "but just {$php(CONSTANT_NAME)} should also work";
0

精彩评论

暂无评论...
验证码 换一张
取 消