2013-05-09 28 views
0

讓我們說我有一個文件夾包含3個文件; file1.php,file2.php,file3.php。 在同一個文件夾中,我有index.php,我想爲每個文件生成切換案例。基於文件夾內容生成PHP開關

$files = array(); 
$folder = opendir(realpath(dirname(__FILE__))); 
while ($file = readdir($folder)) { 
    if (strpos($file, '.php') !== false && $file !== 'index.php') { 
     array_push($files, $file); 
    } 
} 

$switch = $_GET['component']; 
switch($switch) { 
    foreach ($files as $file) { 
     case str_replace('.php', '', $file):  include_once($file);    break; 
    } 
} 

我想我的情況下,看起來像在最後:

$switch = $_GET['component']; 
switch($switch) { 
     case file1:  include_once('file1.php');    break; 
     case file2:  include_once('file2.php');    break; 
     case file3:  include_once('file3.php');    break; 
} 
+0

我不知道我有你想在這裏從長遠來看,要達到什麼合適的概述...所以...只是爲了確認:你有大量的文件,並將這些文件代表組件。根據URL中提供的組件,您想要包含不同的文件?你只能在頁面上有一個組件,而不是多個組件? – 2013-05-09 19:10:54

回答

4

嗯......好像曲給我。

if(in_array($_GET['component'].".php",glob("*.php")) && $_GET['component'] != "index") 
    include_once($_GET['component'].".php"); 
+0

+1簡單和優雅 – kapa 2013-05-09 19:15:10

+0

+1給你,如果它真的很好。但是如果你可以檢查'$ _GET ['component']'的值並檢查文件是否存在,那麼它是完美的。 – ncm 2013-05-09 19:16:50

+0

謝謝!正是我需要的,但與小mods :) – EibergDK 2013-05-09 19:43:42