所以这一切都源于不想在一个巨大的If语句中检查每个POST,其中有大量的AND这样:
if(isset($_POST[$question], $_POST[$choice1], $_POST[$choice2], $_POST[$choice3], $_POST[$choice4], $_POST[$choice5], $_POST[$password]) &&
strlen(question > 0) &&
strlen(choice1 > 0) &&
strlen(choice2 > 0) &&
strlen(choice3 > 0) &&
strlen(choice4 > 0) &&
strlen(choice5 > 0) &&
strlen(password > 0))
{
$cat=$_POST['cat'];
$question=$_POST['question'];
$choice1=$_POST['choice1'];
$choice2=$_POST['choice2'];
$choice3=$_POST['choice3'];
$choice4=$_POST['choice4'];
$choice5=$_POST['choice5'];
$password=$_POST['password'];
}
else{
//Incorrect password or missing data
}
相反,我创建了一个数组,其中包含我想要检查的每个变量的字符串以及运行我的测试的foreach循环
//create array with all wanted variables
$variables = array('cat', 'question', 'choice1', 'choice2', 'choice3', 'choice4', 'choice5', 'password');
$returnError = FALSE;
//run through array to check that all have been posted and meet requirements
foreach($variables as $var) {
if(!isset($_POST[$var]) || !strlen($_POST[$var]) > 0) {
$returnError = TRUE;
break;
}
}
现在我想获取字符串名称并实例化具有相同名称的变量
//create array with all wanted variables
$variables = array('cat', 'question', 'choice1', 'choice2', 'choice3', 'choice4', 'choice5', 'password');
$returnError = FALSE;
//run through array to check that all have been posted and meet requirements
foreach($variables as $var) {
if(!isset($_POST[$var]) || !strlen($_POST[$var]) > 0) {
$returnError = TRUE;
break;
}
else{
global $*/variable named $var*/ = $_POST[$var];
}
}
这可能吗?如果没有,我将如何使用类似的变量数组做类似的事情:
$variables = array($cat,$question,$choice1,$choice2,$choice3,$choice4,$choice5,$password);
答案 0 :(得分:1)
您可以使用Variable variables,但不建议这样做。
global $$var = $_POST[$var];
答案 1 :(得分:-1)
使用eval(); http://www.php.net/eval
请注意,使用后期数据中的eval()创建变量可能会带来安全风险。