有办法做到这一点吗?
包括文件:
<?php
$_GET["id"];
case "fruits": include 'fruits.php';
?>
fruits.php:
<?php
$id = 'fruits';
echo 'hello fruits';
?>
我想按照包含文件中指定的ID包含文件。 谢谢你的帮助。
答案 0 :(得分:0)
您的代码非常不完整,但这是尝试解决您的问题。
phone
或者,如果你有一长串可能的文件,我建议如下:
<?php
// Get the ID parameter and change it to a standard form
// (Standard form is all lower case with no leading or trailing spaces)
$FileId = strtolower(trim($_GET['id']));
// Check the File ID and load up the relevant file
switch( $FileId ){
case 'fruits':
require('fruits.php');
break;
case 'something_else':
require('something_else.php');
break;
/* ... your other test cases... */
default:
// Unknown file requested
echo 'An error has occurred. An unknown file was requested.';
}
?>
包含大量案例的切换语句可能会变长,并且会降低可读性。因此,第二个解决方案使用数组,<?php
// Get the ID parameter and change it to a standard form
// (Standard form is all lower case with no leading or trailing spaces)
$FileId = strtolower(trim($_GET['id']));
// Array of possible options:
$FileOptions = array('fruits', 'something_else', 'file1', 'file2' /* ... etc... */);
// Check if FileId is valid
if(in_array($FileId, $FileOptions, true)){
// FileId is a valid option
$FullFilename = $FileId . '.php';
require($FullFilename);
}else{
// Invalid file option
echo 'An error has occurred. An unknown file was requested.';
}
?>
函数减少代码长度。这也使您可以轻松查看/管理允许的文件。