【问题标题】:Elseif include, and echo an outside variable?Elseif 包含并回显外部变量?
【发布时间】:2011-03-10 22:30:54
【问题描述】:

我有一个 Elseif 语句,它获取一个模板名称并包含包含一个大数组的模板 PHP 文件,它在页面上输出结果。

$template = str_replace("-","_","{$_GET['select']}");
    if ($template == "cuatro"){
        包括(“模板/cuatro.php”);
        回声 $page_output;
    } elseif ($template == "ohlittl"){
        包括(“模板/ohlittl.php”);
        回声 $page_output;
    } 别的 {
        echo "对不起,没有找到模板。";
    }

$page_output = "你选择了$template_select[0]。";

从那里,我收到一条通知,说它找不到 $page_output 变量。

注意:未定义变量:第 10 行 C:\ ... \template.php 中的 page_output

如果我将变量放在包含的文件中,它可以找到它。但我试图让这个变量保留在这个页面上。我该如何完成?

【问题讨论】:

  • "{$_GET['select']}"$_GET['select'] 完全相同,只是更复杂一些。您不需要将已经是字符串的变量放在引号中。

标签: php include


【解决方案1】:

您在回显之后定义$page_output。在您调用 echo $page_output 时,它还不存在。

试试:

$page_output = "You've chosen {$template_select[0]}.";
$template = str_replace("-","_","{$_GET['select']}");
if ($template == "cuatro"){
    include("templates/cuatro.php");
    echo $page_output;
} elseif ($template == "ohlittl"){
    include(dirname(__FILE__) . "/templates/ohlittl.php");
    echo $page_output;
} else {
    echo "Sorry, template not found.";
}

虽然我不知道你是如何设置 $template_select 的,如果你知道它总是会说相同的模板名称?

我认为可以实现您想要的替代方法:

$templates = array('cuatro', 'ohlittl');
$selectedTemplate = strtolower(str_replace("-","_",$_GET['select']));

foreach ($templates as $template)
{
    if ($template === $selectedTemplate) {
       include(dirname(__FILE__) . "/templates/" . $template . ".php");
       echo "You've chosen {$template}.";
    }
}

【讨论】:

  • 在包含之后,我需要从包含的所选文件中输出一些带有变量的代码。当我尝试时,我收到未定义的变量警告,因此几乎不包含包含的文件。有解决办法吗?这几乎是第一种方式,并且 $template_select 是在包含文件中定义的变量,所以不,它不会总是说相同的模板名称。这就是我要解决的问题。
  • 如果你用 echo $aVarOnTheIncludedPage 复制 echo "You've selected {$template}" 是你遇到问题的地方吗?
  • 您确定每个模板文件都包含您要打印的变量吗?
  • 是的,我检查了很多次。
【解决方案2】:

您的模板

  1. 直接输出文本 (echo)
  2. 将结果存储在全局变量(例如$page_output)或局部变量中(包含在函数内部发生,但这对模板是透明的)。
  3. 返回输出(是的,包括可以返回值)。

您似乎想要选项 2,但您的模板没有定义任何 $page_output 变量。也可以直接在模板中输出文本,缓冲输出,赋值给$page_output

ob_start();
include "file.php.inc";
$page_output = ob_get_contents();
ob_end_clean();

【讨论】:

    猜你喜欢
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 2015-01-29
    • 2012-03-28
    相关资源
    最近更新 更多