在PHP中,是否有一种方法可以将常量包含在字符串中,而无需进行连接操作?
define('MY_CONSTANT', 42);
echo "This is my constant: MY_CONSTANT";
在PHP中,是否有一种方法可以将常量包含在字符串中,而无需进行连接操作?
define('MY_CONSTANT', 42);
echo "This is my constant: MY_CONSTANT";
虽然我来晚了,但是如果你不喜欢(s)printf,这里有我的解决方案:
// Can of course be replaced with the const syntax
define("FOO", "bar");
$replace_pairs = ["%myConstant" => FOO];
// Output : "My constant : bar"
echo strtr("My constant : %myConstant", $replace_pairs);
有趣的是你可以使用关键字“const”作为函数名称,以防止命名空间混乱:
define("FOO","foo");
${'const'} = function($a){return $a;};
echo "{$const(FOO)}"; // Prints "foo"
echo const(FOO); // Parse error: syntax error, unexpected T_CONST
你也可以使用 $GLOBALS 在整个代码中传播 'const' 函数:
$GLOBALS['const'] = function($a){return $a;};
不确定是否安全用于未来。更糟糕的是,它仍然看起来很丑陋。
我经常需要在编写脚本时打印新行字符。
从浏览器运行脚本时,换行应为<br>
,而从终端执行时应为PHP_EOL
所以,我会这样做:
$isCLI = ( php_sapi_name() == 'cli' );
$eol = $isCLI ? PHP_EOL : '<br>';
echo "${eol} This is going to be printed in a new line";
这是一个老问题,但对于那些在搜索的人来说,这是另一种解决方法
<?php
define( 'MY_CONSTANT', 'world' );
echo "Hello {${$constant = 'constant'}('MY_CONSTANT')}";
我相信这回答了原帖的问题。唯一的问题是全局索引键似乎只能用小写字母。
define('DB_USER','root');
echo "DB_USER=$GLOBALS[db_user]";
输出:
DB_USER=root
$db_user = 'root';
。 - Jeff Puckett