我不太清楚你如何在沒有實例化Money對象的情況下工作,並且在代碼中存在一些拼寫錯誤。
但是無論如何,從你說的最後一行你想要「訪問錢包裏面的錢」,你的設置似乎沒有多大意義。錢包不是一種金錢,所以它看起來並不是正確的,它正在擴大資金。
如果你想要錢是一類,你可能會改爲使用依賴注入,像這樣:
class Money {
private $amount;
public function add($amount) {
$this->amount += $amount;
}
public function remove($amount) {
$this->amount -= $amount;
}
public function getAmount() {
return $this->amount;
}
}
class Wallet {
private $money; // An Object
public function __construct(Money $money) {
$this->money = $money;
}
public function addMoney($amount) {
$this->money->add($amount);
}
public function removeMoney($amount) {
$this->money->remove($amount);
}
public function getMoney() {
return $this->money->getAmount();
}
}
$money = new Money();
$wallet = new Wallet($money);
$wallet->addMoney(50);
echo $wallet->getMoney(); // displays 50
$wallet->removeMoney(20);
echo '<br>' . $wallet->getMoney(); // displays 30
這樣你的錢,實際上是你的錢包裏,你可以玩你想要的東西。
如果您希望直接使用Money中的函數,則必須更改Wallet類中的$money
對象public
。那麼你可以做這樣的東西:
class wallet {
public $money; // An Object
public function __construct(Money $money) {
$this->money = $money;
}
}
$money = new Money();
$wallet = new Wallet($money);
$wallet->money->add(50);
echo $wallet->money->getAmount(); // displays 50
$wallet->money->remove(20);
echo '<br>' . $wallet->money->getAmount(); // displays 30
改變'$本 - > $錢= $錢;''到$這個 - >錢= $錢;'。 – someOne
還缺少一個';'在線私人$錢//一個對象' – Viral
謝謝,這個想法是用法。我知道後 – Roger