Im в настоящее время пытается сделать небольшую игру в кости в php. Прямо сейчас я пытаюсь сделать "currentscore", где все точки из rand (1,6) сложены в одну переменную.
Вот класс, который я делаю в:
<?php
class CDice {
public $roll;
public $currentscore;
public function Roll()
{
$this->roll = rand(1,6);
return $this->roll;
}
public function currentScore()
{
$this->currentscore += $this->roll;
return $this->currentscore;
}
}
Я не понимаю, почему $this->currentscore += $this->roll;
не работает.
Вы понимаете, что в конце выполнения этого класса никакие ценности не сохраняются правильно? Если вы хотите перенести данные на следующую страницу, вы должны использовать сеансы PHP.
<?php
class CDice {
public $roll;
public $currentscore = 0;
public function Roll(){
$this->roll = rand(1,6);
$this->currentscore += $this->roll;
return $this->roll;
}
public function currentScore(){
return $this->currentscore;
}
public function __construct(){
if(session_status() == PHP_SESSION_ACTIVE){
$this->currentscore = isset($_SESSION['dice.score']) ? $_SESSION['dice.score'] ? 0;
# In PHP 7.0
# $this->currentscore = $_SESSION['dice.score'] ?? 0;
} else {
echo 'session has not been initiated';
}
}
}
session_start();
$tmp = new CDice();
echo $tmp->Roll();
echo $tmp->Roll();
echo $tmp->currentScore();
?>
Также не присваивая переменную "initalial" переменной, прежде чем пытаться добавить к ней вещи с помощью + =, - = и т.д., PHP вызывает предупреждение.
$this->currentscore
сначала с 0.$dice = new CDice(); for ( $i=0; $i<3; $i++) echo "Rolled ", $dice->Roll(), " score: ", $dice->currentScore(), "<br/>\n";
Хотя на вашем месте я быcurrentScore
вRoll()
;currentScore()
несколько раз продолжит добавлять последний бросок.