簡體   English   中英

我如何在數組中運行PHP代碼?

[英]How can i run php code within array?

即時通訊使用此PHP代碼(從這里的問題):

<?php

define(TEMPLATES_LOCATION, 'templates/');

function TemplateFunction ($template, $replaces) {
    $template = file_get_contents(TEMPLATES_LOCATION . $template);
    if (is_array($replaces)) {
        foreach($replaces as $replacekey => $replacevalue){
            $template = str_replace('{$' . $replacekey . '}', $replacevalue, $template);
        }
    }
    return $template;
}

$keys = array(
    'TITLE' => 'This is page title',
    'HEADER' => 'This is some header',
    'GALLERY' => 'php while loop here'
);

echo TemplateFunction('body.tpl', $keys);

?>

模板文件的設置方式為以下HTML:

<body>
<div id="gallery">{GALLERY}</div>
</body>

因此在{GALLERY}所在的位置,php腳本應將其替換為我自動生成的<li><img src="images/'.$filename.'"/></li> ,該代碼正在從生成的while循環中運行mysql請求

我認為可能有效的是:

$keys = array(
        'TITLE' => 'This is page title',
        'HEADER' => 'This is some header',
        'GALLERY' => 'while($row = mysql_fetch_array($result)){<li><img src="'.$row['filename'].'"/></li>})'
);

但它不:(

重新輸入您的代碼:

$keys = array(
        'TITLE' => 'This is page title',
        'HEADER' => 'This is some header',
        'GALLERY' => 'while($row = mysql_fetch_array($result)){<li><img src="'.$row['filename'].'"/></li>})'
);

我認為以這種方式將PHP代碼嵌入模板數據中是非常糟糕的做法。 請允許我為您提供完全不同的解決方案...

首先,我們需要封裝代碼。 上面顯示的代碼試圖從$result變量中獲取數據,但是$result本身顯然是在其他位置設置的。 這不是很好,因為如果我們想更改圖庫功能的工作方式,則需要在整個代碼中進行搜索以查找其中的不同部分。

相反,您應該將該功能編寫為自包含功能(如果單個功能過於復雜,則編寫一個類),該功能將加載數據並進行處理。

我們將該函數loadGallery() 它可能看起來像這樣:

function loadGallery() {
    $output = '';
    $result = mysql_query('...gallery query here...');
    while($row = mysql_fetch_array($result)) {
        $output .= "<li><img src='{$row['filename']}'/></li>";
    }
    return '<ul>'.$output.'</ul>';
}

顯然,它可能比這復雜得多(例如,您可能想對其進行分頁或提供類別選項;這些將作為函數的參數編寫)。 為了簡潔起見,我也沒有在此處編寫任何錯誤檢查。

現在已經有了該功能,您可以將其插入模板引擎。 您需要在模板中引用該函數。

您目前有這樣的模板標記{TITLE} 在您的代碼中,這些標記使用str_replace()與純文本交換。 沒關系。 但是在這種情況下,我們現在想調用一個函數,因此我們需要使用另一種標記。

讓我們這樣編寫圖庫標記: {FUNCTION:loadGallery}而不是當前的{GALLERY}

現在,您可以在模板引擎中添加一些代碼,這些代碼可以查看這些{function:}標記並將其替換為函數調用。 (當然,您也可以保留現有的簡單str_replace()方法)

$funcReplaces = array(   //similar to your existing $keys array, but for allowed functions
    'loadGallery'
);

foreach($funcReplaces as $replaceFunc){
    $template = str_replace('{function:' . $replaceFunc . '}', $replaceFunc(), $template);
}

這將運行該函數並將輸出放入模板中。

這樣就為您解答了這個問題。

但是,我應該指出的是,從技術和安全的角度來看,編寫模板引擎時還需要考慮許多其他問題。 上面描述了解決當前特定問題的基本方法,但這並不是一個奇妙的單打全舞模板引擎。 它仍然只是一個非常基本的。

很好,如果這就是您所需要的,但是如果您希望這個系統能夠發展,那么值得注意的是,這整個領域是其他人已經解決並很好解決的一個問題。 有幾個非常好的PHP模板引擎。 我建議您最好的做法是調查其中一些,並可能使用其中一種而不是自己編寫。

您可以嘗試的一些方法:

希望能有所幫助。

您不能“在數組中執行PHP代碼”。 您只需以編程方式構建數組:

while (/* something */) {
    $keys['GALLERY'][] = $something;
}

我發現我編寫的以下代碼是解決問題的正確方法:

$gallery = array();
while($row = mysql_fetch_assoc($result))
{
   $gallery[] = '<li><a href="'.$row['gallery_image_filename'].'" target="_blank"><img src="'.$row['gallery_image_filename'].'" width="'.$final_image_width.'" height="auto" style="margin: '.$other_margin.'px '.$gallery_image_margin.'px '.$other_margin.'px 0px"/></a></li>';
}
$gallery = implode(' ', $gallery);

然后,我可以將$ gallery變量連接到'GALLERY' => 'value'值中,並根據需要輸出所有數據庫結果。 感謝大家的幫助 :)

好了,您可以使用__toString magic方法創建一個classclass將處理畫廊中的所有圖像,然后返回字符串。

   class TemplateGallery{
       private $images = array();

       public function addImage($src){
           $images[] = $src;
       }

       public function __toString(){
           $str = "";
           foreach($images as $image){
               $str .= sprintf('<li><img src="%s"></li>',$image);
           }
           return $str;
       }
   }

嗯,正如評論中的人所說,它太“難”了,因此,您可以使用“預處理”功能,該功能將處理圖像數組,然后返回模板字符串。

$images = array(/* Put images src here */);
function processGallery($images){
    $str = "";
    foreach($images as $image){
        $str .= sprintf('<li><img src="%s"></li>',$image);
    }
    return $str;
}

然后在您的array上調用該函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM