构造函数显示正确值后,getter无法正常工作

时间:2013-09-02 02:25:54

标签: php oop constructor

这看起来很简单。我基本上操纵输入文本文件并尝试以特定格式输出文件。在我能做到之前,我需要$team->getWins getter来返回正确的值。输入文件的格式是团队名称,胜利,损失。以下是输入文本文件mlb_nl_2011.txt

Phillies 102 60
Braves 89 73
Nationals 80 81
Mets 77 85
Marlins 72 90
Brewers 96 66
Cardinals 90 72
Reds 79 83
Pirates 72 90
Cubs 71 91
Astros 56 106
DBacks 94 68
Giants 86 76
Dodgers 82 79
Rockies 73 89
Padres 71 91

以下是Team.php文件:

<?php

class Team {

  private $name;
  private $wins;
  private $loss;

  public function __construct($name, $wins, $loss) {
    $this->name = $name;
    $this->wins = $wins;
    $this->loss = $loss;

    echo $this->name ." ";
    echo $this->wins ." ";
    echo $this->loss ."\n";
  }

  public function getName() {
    return $this->name;
  }

  public function getWins() {
    return $this->wins;
  }

  public function getLosses() {
    return $this->loss;
  }

  public function getWinPercentage() {
    return $this->wins / ($this->wins + $this->loss);
  }

  public function __toString() {
    return $this->name . " (" . $this->wins . ", " . $this->loss . ")";
  }

}

?>

这是我的主要 PHP 文件。

<?php

include_once("Team.php");

  $file_handle = fopen("mlb_nl_2011.txt", "r");

  $teams = array();
  $counter = 0;

  while(!feof($file_handle)) { 
            $line_data = fgets($file_handle);
            $line_data_array = explode(' ',trim($line_data));
            $team = new Team($line_data_array[0],$line_data_array[1],$line_data_array[2]);
            $teams[$counter] = $team;
            $counter++;
  }

  print_r($teams);
  //looks good through this point

  $output_file = "mlb_nl_2011_results.txt";
  $opened_file = fopen($output_file, 'a');

  foreach($teams as $team) {
    $win = $team->getWins();
    $los = $team->getLosses();
    echo $win ." ". $los."\n";
    $name = $team->getName();
    echo fprintf($opened_file, "%s  %d\n", $name, $win_per);
  }
  fclose($opened_file);

?>

在我执行print_r($teams)时,所有值都是正确的。我为每个团队得到了类似的印刷品:

[15] => Team Object
        (
            [name:Team:private] => Padres
            [wins:Team:private] => 71
            [loss:Team:private] => 91
        )

但是当我在echo $win ." ". $los."\n";进行打印时,我得到了这个:

102 60
1289 73
1080 81
1377 85
872 90
1196 66
1190 72
1379 83
872 90
1171 91
856 106
1094 68
1086 76
1082 79
1173 89
1171 91

任何想法??

1 个答案:

答案 0 :(得分:0)

每行开头的意外数字(第一行除外)是此声明的结果......

echo fprintf($opened_file, "%s  %d\n", $name, $win_per);

... as fprintf返回写入流的字符串的长度,echo将此结果发送到标准输出(在这种情况下,显然是屏幕)。因此,例如,您为第二行打印了'12',紧接着是'89 73\n'部分。

解决方案也很明显:在这里摆脱echo。实际上,在实际代码中使用echo print ... ;构造很少是个好主意。 )