mercredi 24 décembre 2014

Understanding Object Instances and Creation in PHP

I've been working through Kent Beck's Test Driven Development by Example, and rewriting the examples in PHP as an exercise in learning the language.


Chapter 2, "Degenerate Objects", describes rewriting a class method and unit test to ensure a new object (in the example, the object is called Dollar) returns each time a method is called (in the example, it's called times).


So far, my class looks like this:



class Dollar {

public $amount;

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

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


And my test looks like this:



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);
}


The first assert passes. The second assert fails with a return of 30.


Conceptually I know why it's returning 30, but I'm not sure how to rewrite the times method to ensure a new Dollar object is correctly instanced and returned. How can I rewrite the times method? Why is $product not a new object instance the second time I call $five->times(3)?


EDIT - I found some examples of the book rewritten in PHP here at SO, but I didn't come across any that described this situation (or clarified, to me, why $product didn't have a new object assigned to it).


Aucun commentaire:

Enregistrer un commentaire