An object of class Dollar cannot be converted to int

I read a book called Test Development by Example by Kent Beck.

I am trying to write a similar function in php but don't understand the steps.

Original Function:

Test function:

public void testEquality() { assertTrue(new Dollar(5).equals(new Dollar(5))); assertFalse(new Dollar(5).equals(new Dollar(6))); } 

Class function:

 public boolean equals(Object object) { Dollar dollar = (Dollar) object; return amount == dollar.amount; } 

My code is:

Test function:

 public function setup() { $this->dollarFive = new Dollar(5); } public function testEquality() { $this->assertTrue($this->dollarFive->equals(new Dollar(5))); } 

Class function:

 class Dollar { public function __construct($amount) { $this->amount = (int) $amount; } public function equals(Dollar $object) { $this->Object = $object; return $this->amount == $this->Object; } } 

When I run the test case, I get the following error.

An object of class Dollar cannot be converted to int

You need help. How can i fix this?

+6
source share
1 answer
 return $this->amount == $this->Object; 

$this->amount is int, $this->Object not int. You tried to compare each other, so you get

An object of class Dollar cannot be converted to int

You probably mean

 return $this->amount == $this->Object->amount; 

However, there is something interesting in your class

 class Dollar { public $amount = 0; // <-- forgotten public function __construct($amount) { $this->amount = (int) $amount; } public function equals(Dollar $object) { $this->Object = $object; // <--- ?!? return $this->amount == $this->Object; } } 

you probably just want

  public function equals(Dollar $object) { return $this->amount == $object->amount; } 
+6
source

Source: https://habr.com/ru/post/910155/


All Articles