php - 我正在制作一个琐事游戏。每个答案都会显示正确的页面。我该如何解决?
问题描述
<?php
if(array_key_exists('button1', $_POST)) {
button1();
}
if(array_key_exists('button2', $_POST)) {
button2();
}
if(array_key_exists('button3', $_POST)) {
button3();
}
if(array_key_exists('button4', $_POST)) {
button4();
}
function button1() {
if ($correct == $answer1){
header("Location: correct.php");
}
else
{header("Location: wrong.php");
}
}
function button2() {
if ($correct == $answer2){
header("Location: correct.php");
}
else {
header("Location: wrong.php");
}
}
function button3() {
if ($correct == $answer3){
header("Location: correct.php");
}
else {
header("Location: wrong.php");
}
}
function button4() {
if ($correct == $answer4){
header("Location: correct.php");
}
else {
header("Location: wrong.php");
}
}
?>
<form method="post">
<input type="submit" name="button1"
class="button" value="<?php echo $answer1?>" />
<input type="submit" name="button2"
class="button" value="<?php echo $answer2?>" />
<input type="submit" name="button3"
class="button" value="<?php echo $answer3?>" />
<input type="submit" name="button4"
class="button" value="<?php echo $answer4?>" />
</form>
这应该将正确答案与他们点击的任何内容进行比较,但由于某种原因,它总是说它是正确的。所有变量都在代码的前面定义,并且来自数据库。我尝试使用 javascript 进行 tis 但是我所有的变量都在 php 中,所以我无法比较答案。
解决方案
当您测试答案时,您正在初始化超出范围的变量。
您有一些代码相当于:
$answer1 = 1;
$correct = 2;
button1();
function button1() {
if ($correct == $answer1){
header("Location: correct.php");
}
else
{header("Location: wrong.php");
}
}
在顶部初始化的变量超出了函数的范围。PHP 将函数内部的变量视为未定义的(因为它们没有被初始化)并将它们都赋值为 value null
。因此测试通过,correct.php
页面被加载。
您根本不需要这里的函数调用。你可以这样做
if(array_key_exists('button1', $_POST)) {
if ($correct == $answer1){
header("Location: correct.php");
}
else {
header("Location: wrong.php");
}
}
不过,我怀疑这里的真正解决方案从一开始就涉及不同的方法。
看看关于变量范围的 PHP 页面
推荐阅读
- javascript - Javascript 不跟踪 DOM 更改
- javascript - js concat函数和spread算子合并/插入有什么区别吗?
- c# - 调试和运行时不同的 InvalidOperationException 行为
- google-chrome-extension - 如何收听 Chrome 扩展中点击的网页的警报框
- angular - 从 Angular 8 中的 Observable 获取最后一个值
- javascript - Typeahead afterselect 填充到另一个输入文本
- docker - Openshift 重新部署失败的最新部署配置
- python - 高基数特征的方差分析
- json - react native 2 下拉列表取决于第一个
- python-3.x - 无法将 s3 与来自 aws lambda 的 ec2 文件夹同步