【发布时间】:2012-01-04 18:55:10
【问题描述】:
define('PREFIX', '/holiday');
$body = <<<EOD
<img src="PREFIX/images/hello.png" /> // This doesn't work.
EOD;
【问题讨论】:
define('PREFIX', '/holiday');
$body = <<<EOD
<img src="PREFIX/images/hello.png" /> // This doesn't work.
EOD;
【问题讨论】:
取自the documentation regarding strings
DEFINE('PREFIX','/holiday');
$const = PREFIX;
echo <<<EOD
<img src="{$const}/images/hello.png" />
EOD;
【讨论】:
$const/images/hello.png 也可以。
$consts = get_defined_constants(); 获取所有定义,然后使用{$consts['PREFIX']} 访问。
如果你有超过 1 个常量,变量的使用会很困难。所以试试这个方法
define('PREFIX', '/holiday');
define('SUFFIX', '/work');
define('BLABLA', '/lorem');
define('ETC', '/ipsum');
$cname = 'constant'; // if you want to use a function in heredoc, you must save function name in variable
$body = <<<EOD
<img src="{$cname('PREFIX')}/images/hello.png" />
<img src="{$cname('SUFFIX')}/images/hello.png" />
<img src="{$cname('BLABLA')}/images/hello.png" />
<img src="{$cname('ETC')}/images/hello.png" />
EOD;
【讨论】:
heredoc 语法中使用的常量不会被解释!
编者注:这是真的。 PHP 无法识别 来自 heredoc 块中任何其他字符串的常量。
【讨论】: