2012-10-28 95 views
-1

我在页面上有下面的代码基本上我想要做的是填充$content变量使用函数pagecontentpagecontent函数中的任何内容都应该添加到$content变量中,然后我的主题系统将采用该$content并将其放入主题中。从下面的答案看来,你们认为我想要的是实际功能中的html和php。如何使用函数填充变量?

下面的这个函数是pagecontent,是我目前试图用来填充$ content的东西。

function pagecontent() 
{ 
     return $pagecontent; 
} 

<?php 

    //starts the pagecontent and anything inside should be inside the variable is what I want 
    $content = pagecontent() { 
?> 

I want anything is this area whether it be PHP or HTML added to $content using pagecontent() function above. 


<?php 

    }///this ends pagecontent 
    echo functional($content, 'Home'); 

?> 
+0

输出缓冲 –

+0

我还在学习代码,所以我不知道那是什么病,现在谷歌,并希望你给我一个回应就可以了藏汉 – leanswag

+0

重构的代码。将内容移至他的功能。 – 2012-10-28 18:29:57

回答

1

我想你正在寻找输出缓冲。

<? 

// Start output buffering 
ob_start(); 

?> Do all your text here 

<? echo 'Or even PHP output ?> 
And some more, including <b>HTML</b> 

<? 

// Get the buffered content into your variable 
$content = ob_get_contents(); 

// Clear the buffer. 
ob_get_clean(); 

// Feed $content to whatever template engine. 
echo functional($content, 'Home'); 
+0

哇这个作品,但弄乱了我的标题 – leanswag

+0

是的,它只是抓住了它的任何方式。 :)我不会经常使用输出缓冲。如果您从其他代码使用此代码调用代码,则会遇到麻烦。输出缓冲是不适合嵌套的,这使得它可能会在更大,更复杂的网站中使用。 – GolezTrol

+0

它的工作原理和即时计划在很多页面上使用,这将是一个问题? – leanswag

1

正如你显然是一个初学者,这里是一个简化的工作版本,让你开始。

function pageContent() 
{ 
    $html = '<h1>Added from pageContent function</h1>'; 
    $html .= '<p>Funky eh?</p>'; 
    return $html; 
} 

$content = pageContent(); 
echo $content; 

您发布的其他代码对您的问题是多余的。首先获得最低限度的工作,然后从那里继续前进。

+0

不是我需要的东西我想$ content = pageContent(){和任何在这里}被添加到$ content – leanswag

+0

@leanswag看我的编辑,但它似乎是一个浪费的步骤。你的电话虽然:)另外,我的原始版本更具可读性。 – vascowhite

1

方式1:

function page_content(){ 
    ob_start(); ?> 

    <h1>Hello World!</h1> 

    <?php 
    $buffer = ob_get_contents(); 
    ob_end_clean(); 
    return $buffer; 
} 

$content .= page_content(); 

方式2:

function page_content(& $content){ 
    ob_start(); ?> 

    <h1>Hello World!</h1> 

    <?php 
    $buffer = ob_get_contents(); 
    ob_end_clean(); 
    $content .= $buffer; 
} 


$content = ''; 
page_content($content); 

方式3:

function echo_page_content($name = 'John Doe'){ 
    return <<<END 

    <h1>Hello $name!</h1> 

END; }

echo_page_content();