【问题标题】:How to use constants with Complex (curly) syntax?如何使用复杂(卷曲)语法的常量?
【发布时间】:2011-04-08 05:10:03
【问题描述】:

我很惊讶地发现以下内容没有按预期工作。

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?";

但我不想连接字符串,与其说是为了性能,不如说是为了可读性。

【问题讨论】:

  • 如果它不起作用,那么它就不起作用。通过更改PHP源并重新编译来解决它。 :-)
  • 如果{CONST_TEST} 在字符串内部,则更不清晰。而是使用串联。
  • stereofrog:是的,PHP 充满了黑客特性、优美的语法和随心所欲的编程——你会感到惊讶!

标签: php constants curly-braces


【解决方案1】:

不,这是不可能的,因为 php 会认为 CONST_TEST 只是单引号/双引号内的 字符串。为此,您必须使用 串联

echo "What is the value of ".CONST_TEST." going to be?";

【讨论】:

  • 感谢您的解释,我认为 php 会解决大括号内的所有问题.. 但我发现这只适用于 $ 变量。
  • 是的。它只适用于以 $ 开头的东西。例如。 {Class::static} 也不起作用 :(
【解决方案2】:

我不明白你为什么要大惊小怪,但你总是可以这样做:

define('CONST_TEST','Some string');
$def=CONST_TEST;
echo "What is the value of $def going to be?";

【讨论】:

  • 我不认为我在大惊小怪,只是好奇:)
  • 在我的例子中,我生成了文件,所有的数据库列和表名都作为类常量。我目前必须为我使用的每个函数中的每个常量创建一个单独的变量。这就是我最终要做的,但这很无聊
【解决方案3】:

这可能是不可能的,但由于您的目标是可读性,您可以使用 sprintf/printf 来获得比通过字符串连接更好的可读性。

define('CONST_TEST','Some string');
printf("What is the value of %s going to be?", CONST_TEST);

【讨论】:

  • 不错!没想到这个
【解决方案4】:

如果您非常想要该功能,您可以使用反射编写一些代码来查找所有常量及其值。然后将它们设置在像$CONSTANTS['CONSTANT_NAME']... 这样的变量中,这意味着如果你想在字符串中放置一个常量,你可以使用{}。此外,与其将它们添加到$CONSTANTS,不如将​​其设为实现数组访问的类,这样您就可以强制其中的值不能以任何方式更改(只有添加到对象中的新元素才能作为数组访问) .

所以使用它看起来像:

$CONSTANTS = new constant_collection();

//this bit would normally be automatically populate using reflection to find all the constants... but just for demo purposes, here is what would and wouldn't be allowed.
$CONSTANTS['PI'] = 3.14;
$CONSTANTS['PI'] = 4.34; //triggers an error
unset($CONSTANTS['PI']); //triggers an error
foreach ($CONSTANTS as $name=>$value) {
    .... only if the correct interface methods are implemented to allow this
}
print count($CONSTANTS); //only if the countable interface is implemented to allow this

print "PI is {$CONSTANTS['PI']}"; //works fine :D

为了让你只需要输入几个额外的字符,你可以使用 $C 而不是 $CONSTANTS ;)

希望对您有所帮助,斯科特

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 2011-10-12
    • 2023-04-07
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多