开发者

Elseif include, and echo an outside variable?

开发者 https://www.devze.com 2023-01-06 06:22 出处:网络
I have an Elseif statement, which gets a template name and includes the template开发者_StackOverflow PHP file which contains a large array, it outputs the result on the page.

I have an Elseif statement, which gets a template name and includes the template开发者_StackOverflow PHP file which contains a large array, it outputs the result on the page.

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

$page_output = "You've chosen $template_select[0].";

From there, I get a notice saying it couldn't find the $page_output variable.

Notice: Undefined variable: page_output in C:\ ... \template.php on line 10

It can find it if I put the variable in the included file though. But I'm trying to get this variable to remain on this page. How do I complete this?


You are defining $page_output after you are echoing it. At the time you call echo $page_output it doesn't exist yet.

Try:

$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.";
}

Although I have no idea how you are setting $template_select and if you are aware it will always say the same template name?

An alternative approach that I believe achieves what you want:

$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}.";
    }
}


Either your template

  1. Outputs the text directly (echo)
  2. Stores the result in a global (e.g. $page_output) or a local variable (in the include happens inside a function, but that's transparent for the template).
  3. Returns the output (yes, includes can return values).

You seem to want option 2, yet your templates are not defining any $page_output variable. You could also output the text directly in the templates, buffer the output, and assign it to $page_output:

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

精彩评论

暂无评论...
验证码 换一张
取 消