将常量(非变量)插入到“heredoc”中
考虑:
<?php
define('my_const', 100);
echo <<<MYECHO
<p>The value of my_const is {my_const}.</p>
MYECHO;
?>
如果我在大括号内放一个变量,它就会打印出来。但不是常数。我该怎么做?
考虑:
<?php
define('my_const', 100);
echo <<<MYECHO
<p>The value of my_const is {my_const}.</p>
MYECHO;
?>
如果我在大括号内放一个变量,它就会打印出来。但不是常数。我该怎么做?
还可以通过将常量的值赋给变量来处理该问题。
就我个人而言,我这样做是因为如果你的字符串中有很多常量,那么你的sprintf()调用可能会非常混乱。然后,扫描字符串并查看正在做什么也变得更加困难。此外,通过单独分配变量,您可以看到什么正在获取什么值。
例如:
$const = CONST;
$variable = VARIABLE;
$foo = (new Foo)->setFooProperty(12)->getFooProperty();
$bar = (123 - 456) * 10;
$ten = 1 + 2 + 1 + (5 - 4);
<<<EOD
Lorem ipsum dolor sit amet, **$variable** adipiscing elit.
Duis gravida aliquet dolor quis gravida.
Nullam viverra urna a velit laoreet, et ultrices purus condimentum.
Ut risus tortor, facilisis sed porta eget, semper a augue.
Sed adipiscing erat non sapien commodo volutpat.
Vestibulum nec lectus sed elit dictum accumsan vel adipiscing libero.
**$const** vehicula molestie sapien.
Ut fermentum quis risus ut pellentesque.
Proin in dignissim erat, eget molestie lorem. Mauris pretium aliquam eleifend.
**$foo** vitae sagittis dolor, quis sollicitudin leo.
Etiam congue odio sit amet sodales aliquet.
Etiam elementum auctor tellus, quis pharetra leo congue at. Maecenas sit amet ultricies neque.
Nulla luctus enim libero, eget elementum tellus suscipit eu.
Suspendisse tincidunt arcu at arcu molestie, a consequat velit elementum.
Ut et libero purus. Sed et magna vel elit luctus rhoncus.
Praesent dapibus consectetur tortor, vel **$bar** mauris ultrices id.
Mauris pulvinar nulla vitae ligula iaculis ornare.
Praesent posuere scelerisque ligula, id tincidunt metus sodales congue.
Curabitur lectus urna, porta sed molestie ut, mollis vitae libero.
Vivamus vulputate congue **$ten**.
EOD;
使用 sprintf()
define('my_const', 100);
$string = <<< heredoc
<p>The value of my_const is %s.</p>
heredoc;
$string = sprintf($string, my_const);