2012-10-28 93 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();