2012-03-29 224 views
0

所以,这一切都源自不想检查每个POST在一个巨大的梗如果用吨与运算的语句,像这样:创建一个从字符串命名变量或创建一个字符串从一个变量命名

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

现在我想利用字符串名称,并使用相同的名称

实例变量

这可能吗?如果没有,我会如何做一些类似变量的数组,如下所示:

$variables = array($cat,$question,$choice1,$choice2,$choice3,$choice4,$choice5,$password); 

回答

1

您可以使用Variable variables,虽然不推荐。

global $$var = $_POST[$var]; 
+0

这会导致解析错误。这样做可以修复它: 'global $$ var; $$ var = $ _POST [$ var];' 非常感谢! – fishpen0 2012-03-29 02:52:52