2011-12-11 67 views
0

我有一點編程經驗,所以從基本的PHP跳轉到使用類,函數等是有點令人生畏。轉換一塊重複的PHP變成一個函數?

我正在構建一個小小的PHP腳本,用於確定用戶通過表單選擇了哪個「主題」,並從該選擇中加載了一些特定的文件。我已經構建了一個工作腳本,但其中有太多的重複,這是一個笑話。

// Add our theme names to variables 
$theme1 = "theme1"; 
$theme2 = "theme2"; 
$theme3 = "theme3"; 

// Test to see what Theme the user chose. 
// Theme 1 
if ($themeChoice==$theme1) 
{ 
    // Load the theme 
    $homepage = file_get_contents('../themes/'.$theme1.'/index.html'); 
    $mobile_js_main = file_get_contents('../themes/'.$theme1.'/js/main.js'); 
    $mobile_js_jquery = file_get_contents('../themes/'.$theme1.'/js/jquery.js'); 
    $mobile_css_easy = file_get_contents('../themes/'.$theme1.'/css/easy.css'); 
    $mobile_images_bg = file_get_contents('../themes/'.$theme1.'/images/bg.png'); 
    $mobile_images_footer = file_get_contents('../themes/'.$theme1.'/images/footer.png'); 
    $mobile_images_nav = file_get_contents('../themes/'.$theme1.'/images/nav.png'); 

    if ($AddPortfolioPage != '') 
    { 
     $portfolioPage = file_get_contents('../themes/'.$theme1.'/portfolio.html'); 
    } 

    if ($AddContactPage != '') 
    { 
     $ContactPage = file_get_contents('../themes/'.$theme1.'/contact.html'); 
    } 

    if ($AddBlankPage != '') 
    { 
     $blankPage = file_get_contents('../themes/'.$theme1.'/blank.html'); 
    }   
} 

然後重複每個主題......這顯然不是一個理想的方法。任何幫助深表感謝!

回答

1

將所有主題放入數組中並循環找到所選主題。

$themes = array("theme1", "theme2", "theme3"); 

foreach($themes as $theme) 
{ 
    if($themeChoice == $theme) 
    { 
     $homepage = file_get_contents('../themes/'.$theme.'/index.html'); 
     $mobile_js_main = file_get_contents('../themes/'.$theme.'/js/main.js'); 
     $mobile_js_jquery = file_get_contents('../themes/'.$theme.'/js/jquery.js'); 
     $mobile_css_easy = file_get_contents('../themes/'.$theme.'/css/easy.css'); 
     $mobile_images_bg = file_get_contents('../themes/'.$theme.'/images/bg.png'); 
     $mobile_images_footer = file_get_contents('../themes/'.$theme.'/images/footer.png'); 
     $mobile_images_nav = file_get_contents('../themes/'.$theme.'/images/nav.png'); 

     if ($AddPortfolioPage != '') 
     { 
      $portfolioPage = file_get_contents('../themes/'.$theme.'/portfolio.html'); 
     } 

     if ($AddContactPage != '') 
     { 
      $ContactPage = file_get_contents('../themes/'.$theme.'/contact.html'); 
     } 

     if ($AddBlankPage != '') 
     { 
      $blankPage = file_get_contents('../themes/'.$theme.'/blank.html'); 
     }   

     break; // Break will exit the loop once the choice is found 
    } 
} 
+0

簡單!謝謝:) – tctc91

+0

for循環完全沒用......他可以使用'in_array()'檢查主題是否在數組中# – shesek

+0

@shesek - 檢查存在不是他的代碼示例的要點。 – nickb