Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试使用PHP堆栈值_Php_Oop - Fatal编程技术网

尝试使用PHP堆栈值

尝试使用PHP堆栈值,php,oop,Php,Oop,我目前正在尝试用php制作一个小骰子游戏。现在我正在尝试做一个“currentscore”,其中一个rand(1,6)中的所有点都被叠加到一个变量中 这是我在做这件事的班级: <?php class CDice { public $roll; public $currentscore; public function Roll() { $this->roll = rand(1,6); return $this->

我目前正在尝试用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;
   }
}

您是否意识到,在这个类的执行结束时,没有正确的值?如果希望将此数据传输到下一个页面呈现,则应使用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抛出警告。

先用0初始化
$this->currentscore
。效果很好。试试这个:
$dice=newcdice();对于($i=0;$iRoll(),“score:”,$dice->currentScore(),“
\n”
如果我是你,我会在
Roll()中更新
currentScore
;多次调用
currentScore()
将继续添加最后一卷。$this->currentScore=0;不起作用:(可能我不清楚,我的目标是将同一轮中每一卷的分数保存到“currentscore”。稍后,当该轮结束时,“currentscore”的分数将移动到“totalscore”。什么是“不工作”?是否有任何错误?在文件顶部添加:
ini\u集(“显示错误”,1);错误报告(E\u ALL)
向我们展示更多的代码,并说明哪些代码不起作用。当我说“不起作用”时,我的意思是“currentscore”不起作用,只显示与当前掷骰相同的值。我明白了,这解释了很多。我确实用意大利面代码制作了这个游戏,并且在所有地方都进行了会话。这应该是一个干净的游戏:)