简体   繁体   中英

Generate PHP switch based on folder content

Let us say I have a folder containing 3 files; file1.php, file2.php, file3.php. In the same folder, I have index.php, which I want to generate switch cases for each file.

$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;
    }   
}

What I would like my cases to look like in the end:

$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;
}

Um... Seems convoluted to me.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM