gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:45:03 26 4
gpt4 key购买 nike

我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com