我正在阅读关于stackoverflow的这个问题:
/programming/104516/calling-php-functions-within-heredoc-strings
并且接受的答案说要做像这样的纯PHP模板:
template.php:
<html>
<头>
<title> <?= $ title?> </ title>
</ head>
<身体>
<?= getContent()?>
</ body>
</ html>
index.php:
<?php
$ title ='演示标题';
函数getContent(){
返回'<p> Hello World!</ p>';
}
include('template.php');
?>
对我来说,以上内容在某种意义上来说并不是很好的结构,即template.php依赖于其他脚本中定义的变量。而且您在执行操作时使用include()执行代码include('template.php')(与使用include()包含未立即执行的类或函数相反)。
我觉得更好的方法是将模板包装在函数中:
template.php:
<?php
功能模板($ title,$ content){
ob_start(); ?>
<html>
<头>
<title> <?= $ title?> </ title>
</ head>
<身体>
<?= $内容?>
</ body>
</ html>
<?php return ob_get_clean();
}
?>
index.php:
<?php require_once('template.php'); 打印模板(“演示标题”,“ <p> Hello World!</ p>”); ?>
第二种方法更好吗?有更好的方法吗?