如何在复杂(花括号)语法中使用常量?

12

我惊讶地发现以下内容的效果与预期不符。

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

但我更倾向于不要连接字符串,这并不完全是出于性能考虑,而更多地是为了可读性。


2
如果它不能工作,那就是不能工作。通过更改PHP源代码并重新编译来解决它。 :-) - Jake N
如果{CONST_TEST}在字符串内部,那么可读性会更差。最好使用连接符。 - Davor Lucic
Stereofrog: 是的,PHP 充满了黑客特性,有漂亮的语法和编写-想什么就写的编程方式——你会感到惊讶! - NikiC
4个回答

7

不可能实现,因为php会将CONST_TEST视为单引号/双引号内的普通字符串。你需要使用连接运算符来实现。

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

谢谢您的解释,我以为 PHP 会解析花括号内的所有内容...但是我发现这只适用于 $ 变量。 - aland
1
是的。这只适用于以 $ 开头的内容。例如,{Class::static} 也不行 :( - NikiC

4

虽然可能不太可能,但是由于你的目标是可读性,你可以使用sprintf / printf来实现比字符串连接更好的可读性。

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

不错!我没想到这个。 - funder7

3
我不明白为什么你非要大惊小怪,其实你可以这样做:
define('CONST_TEST','Some string');
$def=CONST_TEST;
echo "What is the value of $def going to be?";

9
我觉得我没有大惊小怪,只是出于好奇。 :) - aland
在我的情况下,我已经生成了包含所有数据库列和表名称的类常量文件。目前,我必须为每个函数中使用的每个常量创建单独的变量。这就是我最终要做的事情,但这非常无聊。 - Ruan Mendes

1

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

因此,使用它看起来像:

$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 ;)

希望这有所帮助,Scott


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接