您可以使用输出缓冲,如下所示:
<?php ob_start();?>
<ul class="nav megamenu">
<?php if (!$logged) { ?>
<li class="home">
<a href="?route=common/home">
<span class="menu-title">Home</span>
</a>
</li>
<?php } ?>
<?php if ($logged) { ?>
<li class="home">
<a href="?route=subscribers/home">
<span class="menu-title">Home</span>
</a>
</li>
<?php } ?>
<?php
$output = ob_get_contents();
ob_end_clean();
?>
See In Action
使用这种启动缓冲区然后将结果分配给变量的方法非常方便,并且在一些 MVC 框架中使用。
简单的例子:
<?php
/* Assign an array of values that will be passed
* to the loader then extracted into local variables */
$data['logged']=true;
$output = loadContentView('top_nav', $data);
function loadContentView($view, $data=null){
$path = SITE_ROOT.'/path/to/views/'.$view.'.php';
if (file_exists($path) === false){
return('<span style="color:red">Content view not found: '.$path.'</span>');
}
/* Extract $data passed to this function */
if($data != null){
extract($data);
}
ob_start();
require($path);
$return = ob_get_contents();
ob_end_clean();
return $return;
}
?>