私はstackoverflowでこの質問を読んでいた:
/programming/104516/calling-php-functions-within-heredoc-strings
そして受け入れられた答えは、このような単純なPHPテンプレートを実行するように言っています:
template.php:
<html>
<head>
<title> <?= $ title?> </ title>
</ head>
<本体>
<?= getContent()?>
</ body>
</ html>
index.php:
<?php
$ title = 'デモタイトル';
関数getContent(){
return '<p> Hello World!</ p>';
}
include( 'template.php');
?>
私には、template.phpが他のスクリプトで定義された変数に依存するという意味で、上記の構造はうまくありません。また、実行時にコードを実行するためにinclude()をinclude('template.php')使用しています(include()を使用して、すぐには実行されないクラスまたは関数を含めるのとは対照的です)。
テンプレートを関数内にラップするのがより良いアプローチだと思います:
template.php:
<?php
関数template($ title、$ content){
ob_start(); ?>
<html>
<head>
<title> <?= $ title?> </ title>
</ head>
<本体>
<?= $ content?>
</ body>
</ html>
<?php return ob_get_clean();
}
?>
index.php:
<?php require_once( 'template.php'); print template( 'Demo Title'、 '<p> Hello World!</ p>'); ?>
2番目のアプローチはより良いですか?それを行うためのさらに良い方法はありますか?