2017-02-19 78 views
0

代码输出“我将要去洛杉矶,旅程将有300英里的距离,我们需要停下2点。”当它应该根据我的IF语句中定义的数字来拉取单词“stop”的复数或单数时(在这种情况下,它应该是复数)。我猜测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

碰巧有相同答案的不同问题不重复。为了获得一些额外的点而不必要的适度调整会损害Stackoverflow产品。 – Andy

回答

5

您似乎忽视了一个小细节。

if ($this->stops = 1) 

应该

if ($this->stops == 1) 
+0

D'oh,这是我的一个愚蠢的错误......谢谢。 ;) – Andy

2

您的IF语句似乎是错误的。 事实上,它应该是:

if($this->stops == 1){ ...

您必须使用两个==迹象做一个比较,否则是赋值。所以在你的情况下,一个=符号不会真正测试你期望的情况。