php - 使用 PHP 函数缩短重复代码

标签 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['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_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');

关于php - 使用 PHP 函数缩短重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49989116/

相关文章:

php - laravel 根据表单中的多个字段创建一个带有查询的规则

javascript - Javascript 中的 PHP 变量

html - Webgl使用视口(viewport)+剪刀更新区域

javascript - 浏览器默认填充

php - 如何使用 Ajax 将页面内容添加到 div 中?

php - PHP copy() 方法使用远程服务器图像文件的可靠性

javascript - 如何直接链接到特定的 JavaScript 选项卡?

javascript - 如何使用 Javascript 将 HTML 注入(inject)特定的 div

javascript - 在新选项卡中打开我的图像

php - 如果我需要找到两个彼此不接近的词,MySQL 如何进行全文搜索