使用PHP函数缩短重复代码
我在PHP中的代码相当长,我希望通过创建一个具有不同值的函数来缩短代码,而不是只编写一行函数名,而不是许多行代码,但它似乎不起作用 这是重复的代码:使用PHP函数缩短重复代码,php,html,Php,Html,我在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['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'];
}
这就是计划,而不是上面的代码,我会把它写在下面:
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');
但它就是不起作用,当您尝试回显例如变量$meta\u name
时,它显示它是空的。你能帮助我吗?多谢各位
注意:当我不使用该函数并长期使用它时,一切正常,但当我使用该函数时问题就出现了。变量在函数范围内。这就是为什么您不能在函数之外访问它。您可以
返回值:
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.
}
return $_POST[$value]; // return value
}
$ID_user = ifIssetPost('ID_user');
$meta_name = ifIssetPost('meta_name');
$meta_value = ifIssetPost('meta_value');
您可以使用数组来迭代$\u POST变量。如果要使用字符串或包含字符串的其他变量声明变量,则需要使用{}
。像${$value}
$postValues = ["ID_user", "meta_name", "meta_value"];
foreach ($postValues as $value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$_SESSION[$value."_missing"] = "error";
header("location: index.php");
} else {
${$value} = $_POST[$value];
}
}
您还可以使用$$value
,遵循您的规范:
function ifIssetPost($value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$_SESSION[$value.'_chybi'] = "error";
header("location: index.php");
} else {
return $_POST[$value];
}
}
$value = 'ID_user';
$$value = ifIssetPost($value);
echo $ID_user;
$value = 'meta_name';
$$value = ifIssetPost($value);
echo $meta_name;
obv问题您是否发送值?仅供参考。。。您只需要为空
而不需要!isset
empty
检查isset。${$value}
而不是$$value
非常感谢,它可以工作。这是一个如此简单的解决方案…*叹气*…我只需要学习PHP更多。非常感谢。