PHP函数每次将变量加1 [英] PHP function to increment variable by 1 each time

查看:204
本文介绍了PHP函数每次将变量加1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始为有关生物的游戏编写PHP脚本,这里有4个是/否问题,而我试图做的是编写一个函数,该函数将显示2个按钮,分别说是和否,然后分别给出不同的名称.当我运行该函数时,例如yes1和no1,那么下次运行该函数时,按钮的名称将为yes2和no2.

I have started writing a PHP script for a game about creatures, there are 4 yes/no questions and what I am trying to do is write a function that will display 2 buttons that say yes and no and give then different names each time I run the function, for example yes1 and no1, then the next time the function is run the names of the buttons will be yes2 and no2.

我已经尝试过执行此操作,但是它无法正常工作,下面是我到目前为止已完成的代码,我们将不胜感激.

I have attempted to do this already but it is not working correctly, below is the code I have done so far, any help would be much appreciated.

<?php
session_set_cookie_params(2592000);
session_start();
?>

<html>
<head>
<title>Creature Guessing Game</title>
</head>
<body>
<h1>Creature Guessing Game</h1>
<p> Welcome to the creature guessing game! </p>
<p>Click the button below to start or restart the game </p>

<form method="post" action="Creatures.php">
<input type="submit" name="start" value="Start Game" />
</form>
 <?php
 $questions = array('Does the creature live on land?', 'Does it have wings?', 'Does it live near water?', 'Can it fly?');
 function repeat()
 {
 $number = 0;
 $number++;
 echo "<form method ='post' action='Creatures.php'>
<input type='submit' name='yes'.$number value='Yes' />
<input type='submit' name='no'.$number value='No' />
</form>";

 }
//If form not submitted, display form.
if (!isset($_POST['start'])){
?>
<?php
} //If form is submitted, process input
else{ 
switch($_POST)
{
case yes1:
echo $questions[0];
repeat();
break;
case no1:
echo $questions[1];
repeat();
break;
case yes2:
echo $questions[2];
repeat();
break;
case no2:
$questions[3];
repeat();
}
}
?>
</body>
</html>

推荐答案

为此,您需要维护请求之间的状态.

To do this you need to maintain state between requests.

 function repeat() {
      $number = $_SESSION['number'];
      $number++;
      echo "<form method ='post' action='Creatures.php'>
     <input type='submit' name='answer' value='Yes' />
     <input type='submit' name='answer' value='No' />
     </form>";
     $_SESSION['number'] = $number;
 }

开关

   if($_POST['answer']=='Yes') {
      switch($_SESSION['number']) {
            case 1:
            break;
            case 2:
            break;
      }
   } else {
      switch($_SESSION['number']) {
            case 1:
            break;
            case 2:
            break;
      }
   }

这篇关于PHP函数每次将变量加1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆