Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/260.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_Properties - Fatal编程技术网

在PHP中为类属性赋值

在PHP中为类属性赋值,php,properties,Php,Properties,我正在学习的PHP书中的一个例子(说明私有属性)是这样开始的: class Account { private $_totalBalance = 0; public function makeDeposit($amount) { $this->_totalBalance+= $amount; } public function makeWithdrawal ($amount){ if ($amount < $this->_to

我正在学习的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);
?>
类帐户{
私人$\u总余额=0;
公共职能保证金(金额){
$this->_totalBalance+=$amount;
}
公共功能提取(金额){
如果($amount<$this->\u totalBalance){
$this->_totalBalance-=$amount;
}
否则{
死亡(“资金不足
”); } } 公共函数getTotalBalance(){ 返回$this->\u totalBalance; } } $a=新账户; $a->makeDeposit(500); $a->makedrawing(100); echo$a->getTotalBalance(); $a->makedrawing(1000); ?>
我的问题是,为什么在类中而不是在对象中为$\u totalBalance属性赋值?您不希望$totalBalance的值特定于一个对象吗


谢谢您的帮助。

当您调用
$a->makeDeposit()
时,在makeDeposit()内部
$this
$a
相同。如果您有另一个实例(
$b=new Account;
),那么调用
$b->makeDeposit()
将意味着
$this
将与
$b

相同,是什么让您认为它是在类中而不是在对象中分配的?在你的例子中,你只创建了一个实例。你是什么意思?!该值被分配给
$this->\u totalBalance
,并且
$this
是对象。
die()
不应在类中使用,它会破坏封装的目的。改为抛出异常。但它的开始余额为0,对吗?私人$\u totalBalance=0。我不清楚的是为什么类中有一个值(0)。@user这是一个在实例化时设置的默认值。您可以在构造函数中执行相同的操作,例如
public function\uuuu construct(){$this->\u totalBalance=0;}
Err,类和对象肯定是不可互换的。类是一个定义,而对象是一个类的实例。这是真的,但“对象”通常用于表示“实例”以外的其他含义,因此我认为它不是最具描述性的术语。Account肯定不是类和对象。好的,我将删除这一点。我总是调用类以外的对象,根据这一点,在面向对象编程被广泛应用之前,这是很常见的。。。