代码输出"我将前往洛杉矶。旅程将有300英里。我们需要停2站。"当它应该拉出复数或单数的单词"停止"取决于我的IF语句中定义的数字(在这种情况下,它应该是复数)。由于我构建课程的方式,我猜测IF并不像我预期的那样工作。任何帮助修复它将不胜感激。
class trip {
public $destination;
public $distance;
public $unit;
public $stops = null;
public $transport = null;
function __construct($destination, $distance, $unit, $stops, $transport) {
$this->destination = $destination;
$this->distance = $distance;
$this->unit = $unit;
$this->stops = $stops;
$this->transport = $transport;
}
function getTrip() {
$a = "I will be going to " . $this->destination . ". ";
$a .= "The journey will be a distance of " . $this->distance . " " . $this->unit . ". ";
$a .= "We will need to make " . $this->stops;
if ($this->stops = 1) {
$a .= " stop.";
} else {
$a .= " stops.";
}
$a .= "\n";
echo $a;
}
}
$first = new trip('Los Angeles',300,'miles',2,'airplane');
$first->getTrip();
答案 0 :(得分:5)
你好像忽略了一个小细节。
if ($this->stops = 1)
应该是
if ($this->stops == 1)
答案 1 :(得分:2)
您的IF声明似乎错了。 事实上,它应该是:
if( $this->stops == 1){ ...
你必须使用两个==符号进行比较,否则就是一个作业。所以在你的情况下,一个=符号不会真正测试你期望的条件。