PHP:变量不递增

时间:2017-08-03 17:31:35

标签: php

我使用HTML和PHP进行了10轮的Rock,Paper和Scissors游戏。我遇到的唯一问题是$player$comp$round没有增加并始终转到初始值。可能是什么问题?

这是我的PHP部分代码:

<?php  session_start();

if(!isset($_SESSION['use'])) 
{
   header("Location:enter.php");  
}

if (isset($_GET['logout'])) {
    session_destroy();
    unset($_SESSION['username']);
    header("location: enter.php");
}

$Computer='none';
$user_choice='';
$judgelose = array();
$judgewin = array();
$judgedraw = array();

$round=1;
$player=0;
$comp=0;

if(isset ($_POST['choice']))
{

    $Choosefrom= array('Rock', 'Paper', 'Scissors');
    $Choice= rand(0,2);
    $Computer=$Choosefrom[$Choice];
    $user_choice=$_POST['choice'];

    if($user_choice == $Computer){
    array_push($judgedraw, 'Result : Draw');
    }
    else if($user_choice == 'Rock' && $Computer == 'Scissors' || $user_choice == 'Scissors' && $Computer == 'Paper' || $user_choice == 'Paper' && $Computer == 'Rock'){
    array_push($judgewin, 'Result : Win');
    $player++;
    }
    else if($user_choice == 'Rock' && $Computer == 'Paper' || $user_choice == 'Scissors' && $Computer == 'Rock' || $user_choice == 'Paper' && $Computer == 'Scissors'){
    array_push($judgelose, 'Result : Lose');
    $comp++;
    }
}
?>

1 个答案:

答案 0 :(得分:0)

您还需要在会话中存储这些值,否则每次加载页面时都会重置它们。 PHP不会记住页面加载之间的值。这就是会议的目的。您应该检查会话中是否存在该值并获取它。如果它不存在,请设置初始默认值。然后对变量进行许多任何更改,并在最后将它们保存回会话中。例如:

//check if the session for somevalue exists
if(isset($_SESSION['somevalue'])){
    //get it
    $somevalue = $_SESSION['somevalue'];
} else {
    //set a default value if not isset
    $somevalue = 0;
}

//do something with somevalue
$somevalue++;
//continue doing something with somevalue

//at bottom, save somevalue back into session.
$_SESSION['somevalue'] = $somevalue;