在PHP中,HEREDOC字符串声明对于输出html代码块非常有用。你可以通过在变量前面加$来解析变量,但对于更复杂的语法(如$ var [2] [3]),你必须把你的表达式放在{}括号中。
在PHP 5中,这是可能实际上使函数调用中的{}一HEREDOC字符串中括号,但你必须要经过一些工作。函数名称本身必须存储在一个变量中,必须将其称为动态命名函数。例如:
$fn = 'testfunction';
function testfunction() { return 'ok'; }
$string = <<< heredoc
plain text and now a function: {$fn()}
heredoc;
正如你所看到的,这比以下更混乱:
$string = <<< heredoc
plain text and now a function: {testfunction()}
heredoc;
除了第一个代码示例外,还有其他一些方法,比如抛出HEREDOC来调用函数,或者颠倒这个问题并执行如下操作:
?>
<!-- directly output html and only breaking into php for the function -->
plain text and now a function: <?PHP print testfunction(); ?>
后者的缺点是输出直接放入输出流(除非我使用输出缓冲),这可能不是我想要的。
所以,我的问题的本质是:有没有更好的方法来解决这个问题?
发布于 2018-03-19 20:29:58
可以使用:
function fn($data) {
return $data;
}
$fn = 'fn';
$my_string = <<<EOT
Number of seconds since the Unix Epoch: {$fn(time())}
EOT;
https://stackoverflow.com/questions/-100007675
复制相似问题