Php IF语句解析不正确
代码输出“我将去洛杉矶。旅程将是300英里。我们需要停2站。”根据IF语句中定义的数字(在这种情况下,应该是复数),它应该拉取单词“stop”的复数或单数。我猜IF没有像我预期的那样工作,因为我构建类的方式。如果您能帮忙修理,我们将不胜感激Php IF语句解析不正确,php,Php,代码输出“我将去洛杉矶。旅程将是300英里。我们需要停2站。”根据IF语句中定义的数字(在这种情况下,应该是复数),它应该拉取单词“stop”的复数或单数。我猜IF没有像我预期的那样工作,因为我构建类的方式。如果您能帮忙修理,我们将不胜感激 class trip { public $destination; public $distance; public $unit; public $stops = null; public $transport = null; f
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();
你似乎忽略了一个小细节
if ($this->stops = 1)
应该是
if ($this->stops == 1)
你的IF陈述似乎是错误的。 事实上,它应该是:
如果($this->stops==1){…
你必须使用两个==符号来进行比较,否则就是一个作业。因此,在你的情况下,一个==符号并不能真正测试你所期望的条件。D'oh,这对我来说是一个愚蠢的错误……谢谢。;)不同的问题碰巧有相同的答案,但不会重复。为了获得额外的分数,不必要的节制积分会损坏Stackoverflow产品。