在PHP上使用Class是正确的吗?

时间:2015-05-30 07:19:47

标签: php

class Money {
    private $something;
    private $another;

    public function getSomething() {
        return $this->something;
    }

}

class wallet extends Money{
    private $myAnother;
    private $yourAnother;
    private $money // An Object 

    public function setMoney($money) {
        $this->$money = $money;
        return $this;
    }

    public function getMoney() {
        return $this->money; // Object
    }

}

所以,我正在使用它:

$wallet = new Wallet();

print ($wallet ->getMoney()->getSomething());

工作正常!但我不知道这是否是访问电子钱包内的班级Money的正确方法。

2 个答案:

答案 0 :(得分:0)

如果在$money字段中您指的是基类,则;这不是正确的方法。您已经可以访问子类的方法中的基类,因此$money的字段是多余的,您应该删除它。

您可以使用Money方法初始化__construct()课程,因此请将以下内容添加到Money课程中:

function __construct() {
    $this->something = "something";
    $this->another = "another";
    // anything else needed to initialize this object of Money class..
}

wallet类中,除了直接在类中初始化字段外,还需要初始化基类,如下所示:

function __construct() {
    parent::__construct();
    // anything else needed to initialize this object of wallet class..
}

而且,由于getSomething()基类中Money的方法具有public可见性,您可以使用$wallet->getSomething();直接调用它。

答案 1 :(得分:0)

我不太确定如何在没有实例化Money对象的情况下让它工作,并且你的代码中有一些拼写错误。

但无论如何,从你上一行说你想要“获取钱包里面的钱”,你的设置似乎没有多大意义。钱包不是一种钱,所以它扩展钱似乎是不对的。

如果你想让Money成为一个类,你可能会改为使用依赖注入,如下所示:

$money

这样你的钱实际上就在你的钱包里,你可以随心所欲地玩它。

如果您更愿意直接使用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 。然后你可以做这样的事情:

java.lang.Thread