理解PHP中的对象实例和创建

时间:2014-12-24 17:39:42

标签: php unit-testing oop phpunit

我一直在通过Kent Beck的测试驱动开发实例,并将PHP中的示例重写为学习该语言的练习。

第2章,"退化对象",描述了重写类方法和单元测试以确保每次调用方法时返回一个新对象(在该示例中,该对象称为Dollar)(在例如,它被称为时间)。

到目前为止,我的班级看起来像这样:

class Dollar {

public $amount;

public function __construct($amount) {
    $this->amount = $amount;
}

public function times($multiplier) {
    return new Dollar($this->amount *= $multiplier);
}
}

我的测试看起来像这样:

 public function testTimes()
{
    $five = new Dollar(5);
    $product =  $five->times(2);

    $this->assertEquals(10, $product->amount);

    $product = $five->times(3);
    $this->assertEquals(15, $product->amount);
}

第一个断言传递。 第二个断言失败,返回30

从概念上讲,我知道为什么它会返回30,但我不知道如何重写times方法以确保新的Dollar对象被正确实例化并返回。我怎样才能重写时间方法?为什么$product在第二次调用$five->times(3)时不是新的对象实例?

编辑 - 我在SO处发现了一些用PHP重写的书的例子,但是我没有遇到任何描述过这种情况的书(或者澄清了,为什么$ product没有分配给它的新对象)。

1 个答案:

答案 0 :(得分:2)

它正在返回新对象。但是,每次调用amount方法时,您当前都会为原始对象times()属性分配新值。将方法更改为此。

public function times($multiplier) {
    return new Dollar($this->amount * $multiplier);
}