如何把include(php文件)放到变量?

时间:2011-07-08 08:19:40

标签: php variables include themes

我希望主题或模板不像默认一样,然后其他php可以使用它作为主题。但我有问题,我不能把主题变为输出打印前生成的变量。

这里的例子:

主要代码:

$word[0] = "test";
$word[1] = "hello word";
$word[2] = "example";
$word[3] = "wordwordword";
$word[4] = "variable";

while(5)
{
$name = "TEST".$word[$i];
output .= include("theme.php");

$i++;
}
echo "OUTPUT:";
echo "TITLE";
echo $output;

theme.php代码:

hello <?php echo $name; ?>

注意:我知道while循环会中断,但这只是示例代码。因为我使用while(mysql_fetch_array($ result))。感谢

1 个答案:

答案 0 :(得分:4)

那段代码不可行,所以我认为它是伪代码。无论如何,使用PHP中的ob_ *函数解决了这个问题,如下所示。这就是php中大多数模板解析器的工作方式:

<?php
$word = array( );
$word[0] = "test";
$word[1] = "hello word";
$word[2] = "example";
$word[3] = "wordwordword";
$word[4] = "variable";

$i = 0;
for( $i = 0, $j = count( $word ); $i < $j; $i ++ ) {
    $name = "TEST" . $word[$i];

    ob_start( );
    include( 'theme.php' );
    $output .= ob_get_clean( );
}

echo $output;
/**
 * Result:
 * 
 * TESTtest
 * TESThello world
 * TESTexample
 * TESTwordwordword
 * TESTvariable
 */