无法查看从父类继承的属性

时间:2019-03-20 18:52:13

标签: php oop

我用以下变量创建了一个银行帐户类,$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 . "</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());

1 个答案:

答案 0 :(得分:1)

正如您所说,$Balance属性是私有的。私有意味着无法从定义类外部访问它,甚至不能从继承该属性的子类访问它。

<?php
class Foo {
    private $bar="baz";
    public function __construct(){echo $this->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

因此,您有两种选择。您可以改用您的吸气剂:

<?php
class Foo {
    private $bar="baz";
    public function __construct(){echo $this->bar;}
    public function getBar(){return $this->bar;}
}
class Bar extends Foo {
    public function __construct(){echo $this->getBar();}
}
new Foo;
new Bar;

或者,您可以将属性声明为protected而不是private

<?php
class Foo {
    protected $bar="baz";
    public function __construct(){echo $this->bar;}
    public function getBar(){return $this->bar;}
}
class Bar extends Foo {
    public function __construct(){echo $this->bar;}
}
new Foo;
new Bar;

以下任何一项均可提供预期的输出:

baz
baz

有关属性和方法可见性的更多详细信息,请参见documentation here