我正在学习的PHP书中的一个例子(说明私有属性)是这样开始的:
class Account {
private $_totalBalance = 0;
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);
?>
我的问题是,为什么$_totalBalance属性在类而不是对象中分配值?难道您不希望$totalBalance的值特定于一个对象吗?
谢谢你的帮助
当您调用$a->makeDeposit()
时,在makeDeposit()中$this
与$a
相同。如果您有另一个实例($b = new Account;
),那么调用$b->makeDeposit()
将意味着$this
将与$b
相同。