getter在构造函数显示正确值后不工作



这看起来很简单。我基本上是在操作一个输入文本文件,并尝试以特定的格式输出该文件。在此之前,我需要$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  %dn", $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

有什么想法吗??

每行开头的意外数字(第一个除外)都是此语句的结果。。。

echo fprintf($opened_file, "%s  %dn", $name, $win_per);

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

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

最新更新