php 无法将类 Dollar 的对象转换为 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9599776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:14:10  来源:igfitidea点击:

Object of class Dollar could not be converted to int

php

提问by Debashis

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

我正在阅读作者 Kent Beck 写的名为“Test-Driven Development By Example”的书。

I am trying to write a similar function in php but not understanding the steps.

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

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

无法将类 Dollar 的对象转换为 int

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

需要一些帮助。我怎样才能解决这个问题?

回答by KingCrunch

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

$this->amountis an int, $this->Objectisn't an int. You tried to compare each other, thus you'll get

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

Object of class Dollar could not be converted to int

无法将类 Dollar 的对象转换为 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;
   }