这看起来很简单。我基本上是在操作输入文本文件并尝试以特定格式输出文件。在我这样做之前,我需要$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
有任何想法吗??