在变量中包含PHP?

时间:2013-07-01 22:17:07

标签: php

说我有

$output = '';

我希望在双''中包含以下代码。

<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 } ?>

我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

您可以使用输出缓冲,如下所示:

<?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;
}
?>

答案 1 :(得分:1)

我只是改变了我的代码......更容易

感谢所有人的帮助!

<?php

if (!$this->customer->isLogged()) {
$output = '<ul class="nav megamenu"><li class="home"><a href="?route=subscribers/home"><span class="menu-title">Home</span></a></li>';
}else{
$output = '<ul class="nav megamenu"><li class="home"><a href="?route=common/home"><span class="menu-title">Home</span></a></li>';
}

?>