在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 19:03:40
个人而言,我完全不会使用HEREDOC。它只是没有建立一个好的“模板构建”系统。所有的HTML都被锁定在一个有几个缺点的字符串中
得到一个基本的模板引擎,或者只是使用PHP与包括-这就是为什么语言具有<?php
和?>
分隔符。
template_file.php
<html>
<head>
<title><?php echo $page_title; ?></title>
</head>
<body>
<?php echo getPageContent(); ?>
</body>
index.php
<?php
$page_title = "This is a simple demo";
function getPageContent() {
return '<p>Hello World!</p>';
}
include('template_file.php');
https://stackoverflow.com/questions/-100007675
复制相似问题