簡體   English   中英

PHP函數每次將變量增加1

[英]PHP function to increment variable by 1 each time

我已經開始為一個關於生物的游戲編寫一個PHP腳本,有4個是/否問題,我想要做的是編寫一個函數,它將顯示2個按鈕,表示是和否,每次運行時給出不同的名稱該函數,例如yes1和no1,然后在下次運行該函數時,按鈕的名稱將為yes2和no2。

我已經嘗試過這樣做但是它工作不正常,下面是我到目前為止所做的代碼,任何幫助都會非常感激。

<?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>

為此,您需要在請求之間維護狀態。

 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;
      }
   }

我不同意接受的答案:這是一個更簡單的方法,沒有會話:

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

您必須在會話中存儲“號碼”,因為每次提交頁面時它都會丟失其值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM