【发布时间】:2019-08-11 14:02:47
【问题描述】:
我创建了一个带有以下变量的银行账户类,$Balance 变量是私有的,所以我使用 setter 和 getter 函数来访问 balance 的私有属性。
class BankAccount
{
public $HoldersName;
public $AccountNumber;
public $SortCode;
private $Balance = 1;
public $APR = 0;
public $Transactions = []; //array defined.
public function __construct($HoldersName, $AccountNumber, $SortCode, $Balance = 1) //constructor where i.e. HoldersName is the same as the variable $HoldersName.
{ //constructor automatically called when object is created.
echo "Holders Name: " . $this->HoldersName = $HoldersName . "</br>";
echo "Account Number: " . $this->AccountNumber = $AccountNumber . "</br>";
echo "Sort Code: " . $this->SortCode = $SortCode . "</br>";
$this->Balance = $Balance >= 1 ? $Balance : 1;
}
public function set_Balance($Balance) //SET balance.
{
return $this->Balance=$Balance;
}
public function get_Balance() //GET balance.
{
return $this->Balance; //Allows us to access the prviate property of $Balance.
}
}
SavingsAccount 类扩展了 BankAccount,因此它继承了 BankAccount 类的所有内容。我创建了一个函数来计算利息,即余额 6800 * (0.8+0.25) * 1。
class SavingsAccount extends BankAccount
{
public $APR = 0.8;
public $APRPaymentPreference;
public $ExtraBonus = 0.25;
public function CalculateInterest()
{
$this->Balance = $this->Balance * ($this->APR + $this->ExtraBonus) * 1; //this is where i get the error now
}
public function FinalSavingsReturn()
{
}
}
这里我创建了一个SavingsAccount类的实例,余额为6800,我尝试调用函数SavingsAccount::CalculateInterest()却出现了这个错误:
注意未定义的属性:第 42 行的 SavingsAccount::$Balance
//define objects
$person2 = new SavingsAccount ('Peter Bond', 987654321, '11-11-11', 6800); //create instance of class SavingsAccount
echo "<b>Interest:</b>";
print_r ($person2->CalculateInterest());
【问题讨论】: