开发者

Assigning Values to a Class Property in PHP

One of the examples in the PHP book I am learning from (illustrating private properties) starts like this:

class Account {
   private $_totalBalance = 0;
开发者_Go百科
   public function makeDeposit($amount) {
      $this->_totalBalance+= $amount;
   }

   public function makeWithdrawal ($amount){
      if ($amount < $this->_totalBalance) {
         $this->_totalBalance -= $amount;
      }
      else {
         die("insufficient funds <br />" );
      }
   }
   public function getTotalBalance() {
      return $this->_totalBalance;
   }
}

$a = new Account;
$a->makeDeposit(500);
$a->makeWithdrawal(100);
echo $a->getTotalBalance();
$a->makeWithdrawal(1000);
?>

My question is, why is the $_totalBalance property assigned a value in the class rather than the object? Wouldn't you want the value of $totalBalance to be specific to an object?

Thanks for the help.


When you call $a->makeDeposit(), inside makeDeposit() $this is the same as $a. If you had another instance ($b = new Account;) then calling $b->makeDeposit() would mean $this would be the same as $b.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜