如何使用foreach循环在函数内部动态更改全局变量



我想创建一个函数,通过循环动态更改全局变量的值。我试着把global放在$$键后面,但它抛出了一个错误。有可能做到吗?

define('INPUT_FIELDS', array('fullname', 'phone', 'email')); // the input fields names that every form must have
$fullname = $phone = $email = "";
function isPostValid(){
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
foreach ($_POST as $key => $value) {
if( in_array($key, INPUT_FIELDS) ){// only if the key is exists in the inputs we chose
$$key = checkInputsAndValidate($key);
if(!$$key){// if the variable is null then break the loop and make change the variable to false
return false;
break;
}
}
}//END foreach
return true;
}
return false;
}

正如Dave在评论中所说,您必须使用global关键字来引用全局变量。但是,您也应该尝试使您的代码可扩展到更多可能的变量(即,使用数组(。

我建议更改功能,如下所示:

<?php
define('INPUT_FIELDS', array('fullname', 'phone', 'email'));
/** create a global var that holds all form data **/
$FORM = array();
/** initialize $FORM based on defined input fields **/
foreach (INPUT_FIELDS as $key)
$FORM[$key] = false;
function isPostValid(){
/** access global variable $FORM **/
global $FORM;
/** verify POST request **/
if ($_SERVER['REQUEST_METHOD'] !== 'POST')
return false;
/** check all FORM keys for POST values **/
foreach($FORM as $key => $init_value) {
/** How does checkInputsAndValidate() work in your code?
* -> change here if necessary
**/
$new_value = isset($_POST[$key]) ? checkInputsAndValidate($key) : false;
if (!$new_value)
return false;
$FORM[$key] = $new_value;
}
/** if all is OK, return true **/
return true;
}
?>

最新更新