Testin Jast
Testin Jast

Reputation: 39

Trying to add more than one number (OOP)

I'm trying to add more than 1 to the value of ID but it only adds 1 extra even if I press the button again.

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

Upvotes: 2

Views: 23

Answers (1)

miken32
miken32

Reputation: 42711

PHP is stateless. That is, it runs once and then forgets about everything that just happened. Passing values between PHP sessions can be done with session cookies or form input values. Try something like this instead:

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

The value is passed by the form POST to the script. Then the value is passed to the constructor of the object.

Upvotes: 1

Related Questions