无法查看从父类继承的属性
无法查看从父类继承的属性
这个问题已经有了答案:
我创建了一个银行账户类,其中以下变量,$Balance
变量是私有的,因此我使用setter和getter函数来访问余额的私有属性。
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 . ""; echo "Account Number: " . $this->AccountNumber = $AccountNumber . ""; echo "Sort Code: " . $this->SortCode = $SortCode . ""; $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 "Interest:"; print_r ($person2->CalculateInterest());
admin 更改状态以发布 2023年5月23日
就像你所说的一样,$Balance
属性是私有的。私有的意思是它不能从定义类的外部访问,甚至不能从继承该属性的子类中访问。
bar;} public function getBar(){return $this->bar;} } class Bar extends Foo { public function __construct(){echo $this->bar;} } new Foo; new Bar;
如果我们运行此代码,会出现错误:
baz PHP Notice: Undefined property: Bar::$bar in php shell code on line 2
那么,你有两个选择。你可以使用你的 getter 方法:
bar;} public function getBar(){return $this->bar;} } class Bar extends Foo { public function __construct(){echo $this->getBar();} } new Foo; new Bar;
或者,你可以将该属性声明为protected
而不是private
:
bar;} public function getBar(){return $this->bar;} } class Bar extends Foo { public function __construct(){echo $this->bar;} } new Foo; new Bar;
这两种方法都可以得到预期的输出:
baz baz
有关属性和方法的可见性更多详细信息,请参见这里的文档。