在变量中包含include函数

时间:2010-12-11 06:48:26

标签: php html include

我想要包含一个文件 $ includes [content]是一个变量,我想使用include函数。     

$includes[content]="
<form action=\"index.php?view=login&action=login&".iif($rid!="","rid=$rid&")."".$url_variables."\" method=\"post\" onSubmit=\"submitonce(this)\">
<input type=\"hidden\" value=\"$returnTo\" name=\"returnTo\">
Some html in php form.
 <-- I want to add include 'sys/CodeGen.php'; function -->
Some more html in php form.

Ends in
</form></div>

";
?>

如何在include [content]之间添加?

1 个答案:

答案 0 :(得分:0)

我不确定我理解你的问题。我假设你想做这样的事情:

$variable = "some html";
include($variable);

如果是这样的话,我只能说“你不能,你不应该”。

“不能”部分是因为include()函数(及其兄弟)使用传递给它们的值来查找文件并读取它。如果它传递的文件路径以外的任何内容都会失败。这是一件好事。

您要做的是创建一个模板文件,您可以将其包含在您需要的位置。例如:

// form.inc    
<form action="<?php echo $action; ?>">
<input type="hidden" value="$returnTo" name="returnTo">
</form>

以这种方式执行它比尝试将其放入变量要清晰得多。

如果您打算多次调用该模板,并且您担心性能(这是我能想到的唯一合理化的东西),那么您可以在模板中编写一个函数,然后include_once文件。

例如:

// form.inc

<?php
  function writeForm($action) {
?>
    <form action="<?php echo $action; ?>">
    <input type="hidden" value="$returnTo" name="returnTo">
    </form>
<?php
}
?>

这样,您可以调用include_once("form.inc");,当PHP解析文件时,它将创建一个名为writeForm()的函数,您可以根据需要随时调用,而无需每次都从磁盘读取

如果你想要包含一堆很小的代码片段,但又不想有一堆三行文件(再次出于任何原因),那么你总是可以拥有一个“片段” .inc“文件,它定义了我上面概述的所有这些小功能。

您甚至可以进一步将相关的片段组合在一起并创建一个Helper类。

相关问题