类Dollar的对象无法转换为int

时间:2012-03-07 10:33:10

标签: php

我正在阅读作者Kent Beck撰写的名为“以测试为导向的发展”的书。

我正在尝试在php中编写类似的函数但不了解这些步骤。

原始功能:

测试功能:

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

班级职能:

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

我的代码:

测试功能:

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

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

班级职能:

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

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

执行测试用例时,我收到以下错误。

  

类Dollar的对象无法转换为int

需要一些帮助。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:8)

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

$this->amount是一个int,$this->Object不是int。你试图相互比较,因此你会得到

  

类Dollar的对象无法转换为int

你可能意味着

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

但是,你的班级也有一些奇怪的东西

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

你可能只想要

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