我试图在ID的值上添加1以上,但即使再次按下按钮也只会增加1。
<?php
class Game {
public $id = 1;
public function add() {
$this->id++;
}
}
$game = new Game;
echo $game->id;
if (isset($_POST['submit'])) {
$game->add();
echo $game->id;
}
?>
<form method="post" action="">
<input type="text" name="text">
<input type="submit" name="submit">
</form>
答案 0 :(得分:1)
PHP是无状态的。也就是说,它只运行一次,然后就忘记了刚刚发生的一切。在PHP会话之间传递值可以使用会话cookie或表单输入值来完成。尝试这样的事情:
<?php
class Game {
public $id = 1;
public function __construct($id) {
$this->id = $id;
}
public function add() {
$this->id++;
}
}
if (isset($_POST["id"])) {
$the_id = $_POST["id"];
} else {
$the_id = 1;
}
$game = new Game($the_id);
echo $game->id;
if (isset($_POST['submit'])) {
$game->add();
echo $game->id;
}
?>
<form method="post" action="">
<input type="text" name="text">
<input type="hidden" name="id" value="<?=$game->id?>">
<input type="submit" name="submit">
</form>
该值通过POST形式传递到脚本。然后将该值传递给对象的构造函数。