Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object of class Dollar could not be converted to int

Tags:

php

I was going through the book named "Test-Driven Development By Example" By the author Kent Beck.

I am trying to write a similar function in php but not understanding 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:

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

While executing the test case i am getting the following error.

Object of class Dollar could not be converted to int

Need some help on this. How can i fix this?

like image 868
Debashis Avatar asked Mar 07 '12 10:03

Debashis


Video Answer


1 Answers

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

$this->amount is an int, $this->Object isn't an int. You tried to compare each other, thus you'll get

Object of class Dollar could not be converted to int

You probably mean

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

However, there is also something curious 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'll probably want just

   public function equals(Dollar $object) {
     return $this->amount == $object->amount;
   }    
like image 135
KingCrunch Avatar answered Sep 18 '22 14:09

KingCrunch