无论如何,当我自我提交时,有一次设置变量值

时间:2014-04-23 20:15:01

标签: php

我试图用PHP编写这个简单的猜测数字。问题是,一旦我将此表单提交给自己, $ number 变量将再次随机化,而不是保留以前的值。反正是否保持不变?

<?php
    $run_once = true;
    $number = 10;
    $user_input = 1;
    $display_answer = "";

    function seedRandNumber() {
        srand((double) microtime() * 1000000);
        $num = rand(1, 25);
        return $num;
    }

    if ($run_once) {
        $number = seedRandNumber();
        $run_once = false;
    }

    function answer($input) {
        $num = $GLOBALS['number'];
        if ($input == $num) {
           return "You guess it right";
        } else if ($input > $num) {
            return "it is a lower number";
        } else {
            return "it is a high number";
        }
    }

    if (isset($_POST["number"])) {
        $user_input = $_POST["number"];
        $display_answer = answer($_POST["number"]);
    }

    if (isset($_POST["newgame"])) {
        $number = seedRandNumber();
    }

    ?>

    <h1>Guess Number</h1>

<p1>Please enter a number between 1 and 25</p1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"> 
    Number: <input type="text" name="number" value="<?php echo $user_input; ?>"> <input type="submit" name="submit" value="Submit"> <br>
    <p2><?php echo $display_answer; ?></p2><br>
    <br>
    <input type="submit" name="newgame" value="New Game">
</form>

1 个答案:

答案 0 :(得分:0)

您可以在会话中存储您的号码,然后只在需要时创建一个新号码:

start_session();

if(!isset($_SESSION['number']) || isset($_POST['newgame'])) {
    $number = seedRandNumber();
    $_SESSION['number'] = $number;
}
else {
    $number = $_SESSION['number'];
}

你需要把它放在程序的开头。