如何使用复杂(卷曲)语法的常量?
我很惊讶地发现以下内容没有按预期工作。
define('CONST_TEST','Some string');
echo "What is the value of {CONST_TEST} going to be?";
输出: {CONST_TEST} 的值是多少?
有没有办法解决花括号内的常量?
是的,我知道我可以这样做
echo "What is the value of ".CONST_TEST." going to be?";
,但我不想连接字符串,不是为了性能而是为了可读性。
I was surprised to see that the following doesn't work as expected.
define('CONST_TEST','Some string');
echo "What is the value of {CONST_TEST} going to be?";
outputs: What is the value of {CONST_TEST} going to be?
Is there a way to resolve constants within curly braces?
Yes, I am aware I could just do
echo "What is the value of ".CONST_TEST." going to be?";
but I'd prefer not to concatanate strings, not so much for performance but for readability.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,这是不可能的,因为 php 会将
CONST_TEST
视为单/双引号内的一个简单的字符串。为此,您必须使用串联。Nope that's not possible because php will consider
CONST_TEST
to be a mere string inside the single/double quotes. You will have to use the concatenation for that.这可能不可能,但由于您的目标是可读性,因此您可以使用 sprintf/printf 来获得比字符串连接更好的可读性。
It may not be possible, but since your goal is readability, you could use sprintf/printf to achieve better readability than through string concatenation.
我不明白为什么你必须大惊小怪,但你总是可以这样做:
i don't understand why you have to make a big fuss out of it but you can always do:
如果您非常想要该功能,您可以使用反射编写一些代码来查找所有常量及其值。然后将它们设置在像
$CONSTANTS['CONSTANT_NAME']...
这样的变量中,这意味着如果您想将常量放入字符串中,可以使用 {}。另外,不要将它们添加到 $CONSTANTS 中,而是使其成为一个实现 arrayaccess 的类,这样您就可以强制其中的值不能以任何方式更改(只有添加到对象中的新元素才能更改)作为数组访问)。因此,使用它看起来像:
要使您只需要输入一些额外的字符,您可以使用
$C
而不是$CONSTANTS
;)希望有所帮助,斯科特
If you wanted that feature really badly, you could write a little code using reflection that finds all the constants and their values. Then sets them inside a variable like
$CONSTANTS['CONSTANT_NAME']...
this would then mean if ever you want to put a constant in a string you can using {}. Also, rather than add them to$CONSTANTS
, make it a class that implements arrayaccess so you can enforce that the values in it can not be changed in any way (only new elements added to the object which can be accessed as an array).So using it would look like:
To make it so you only have a few extra characters to type you could just use
$C
instead of$CONSTANTS
;)Hope that helps, Scott