面向对象的计数器

时间:2017-02-27 21:13:12

标签: php

<?php 
class Dribble {
  public $shotCount = 0;
  private $shot = false;
  public function shotPosted() {
      $shot = true; 
      if ($shot == true) {
          $shotCount++;
          echo $shotCount;
      }
      if ($shotCount >= 7) {
        exit("You've reached your monthly goal!");
      }
   }
}
$shot1 = new Dribble();
$shot1->shotPosted();
$shot2 = new Dribble();
$shot2->shotPosted();

我对面向对象的PHP有点新意,我目前正处理一个我有点困惑的问题。 任何投入将不胜感激。先感谢您。

2 个答案:

答案 0 :(得分:0)

要访问对象的属性,必须在方法中使用->表示法。因此$shotCount应为$this->shotCount

class Dribble {
  public $shotCount = 0;
  public function shotPosted() {
      $this->shotCount++;
      echo $this->$shotCount;
      if ($this->$shotCount >= 7) {
        echo "You've reached your monthly goal!";
        $this->shotCount = 0;
      }
   }
}

您也不应该在函数中调用exit()。说明说明shotCount应该设置回0,但退出脚本时会丢失所有内容。

答案 1 :(得分:-1)

为此 -

if ($shot = true) { ... }
你可能是这个意思:

if ($shot == true) { ... }

=用于赋值,==用于测试相等性; ===也测试相同类型。