我在PHP中的代码很长,我希望通过创建一个具有不同值的函数来缩短它,而不是只编写一行函数名而不是多行代码,但它似乎不起作用.
这就是重复代码:
if (!isset($_POST['ID_user']) || empty($_POST['ID_user'])) {
$_SESSION['ID_user_missing'] = "error";
header("location: index.php");
} else {
$ID_user = $_POST['ID_user'];
}
if (!isset($_POST['meta_name']) || empty($_POST['meta_name'])) {
$_SESSION['meta_name_missing'] = "error";
header("location: index.php");
} else {
$meta_name = $_POST['ID_user'];
}
if (!isset($_POST['meta_value']) || empty($_POST['meta_value'])) {
$_SESSION['meta_value_missing'] = "error";
header("location: index.php");
} else {
$meta_value = $_POST['meta_value'];
}
Run Code Online (Sandbox Code Playgroud)
这是计划,而不是那个代码,我只会在下面有这个:
function ifIssetPost($value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$_SESSION[$value.'_chybi'] = "error";
header("location: index.php");
} else {
$$value = $_POST[$value];
}
}
ifIssetPost('ID_user');
ifIssetPost('meta_name');
ifIssetPost('meta_value');
Run Code Online (Sandbox Code Playgroud)
但它只是不起作用,当你尝试回$meta_name显示例变量时,它表明它是空的.你能帮助我吗 ?非常感谢你.
注意:当我没有那个功能并且做很长的事情时,一切正常,但问题出现在我使用该功能时.
变量在函数范围内.这就是为什么你不能在函数之外访问它.你可以return的价值:
function ifIssetPost($value) {
if (empty($_POST[$value])) { // Only empty is needed (as pointed out by @AbraCadaver)
$_SESSION[$value.'_chybi'] = "error";
header("location: index.php");
exit; // add exit to stop the execution of the script.
} else {
return $_POST[$value]; // return value
}
}
$ID_user = ifIssetPost('ID_user');
$meta_name = ifIssetPost('meta_name');
$meta_value = ifIssetPost('meta_value');
Run Code Online (Sandbox Code Playgroud)