好吧,我知道了。我知道…这个可能比较简单。但是,我对OOP非常陌生,想学习如何更有效地回收我的代码。
我在php中有一个类,然后另一个类继承了之前的类,像这样
class team {
private $league;
private $team;
public $year = 2013;
function getTeamSeasonRecord($league, $team) {
// Get given's team record thus far
$this->record = $record;
return $record;
}
class game extends team{
public function __construct()
{
global $db;
if($game_league == "mlb")
{
$table = "current_season_games";
} else
{
$table = "".$game_league."_current_season_games";
}
$query = "SELECT * FROM ".$table." WHERE game_id = :game_id";
$stmt = $db->prepare($query);
$stmt->execute(array(':game_id' => $game_num));
$count = $stmt->rowCount();
$this->games_count = $count;
if($count == 1)
{
$this->game_league = $game_league;
$this->game_num = $game_num;
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$home_team = $row['home_team'];
$away_team = $row['away_team'];
$game_int = $row['game_date_int'];
$game_date = $row['game_date'];
$game_time = $row['game_time'];
}
$this->home_team = $home_team;
$this->away_team = $away_team;
$this->game_int = $game_int;
$this->game_date = $game_date;
$this->game_time = $game_time;
}
}
$team_class = new team($this->game_league, $this->home_team, 2013);
$record = $team_class->getTeamSeasonRecord($this->game_league, $this->home_team);
$this->team_record -> $record;
}
既然标题为"game"的类是标题为"team"的类的扩展,那么游戏类不能访问team类范围内的所有功能吗?在团队类中编写的getTeamSeasonRecord()函数将查找任何给定团队的记录。但是,对于游戏课,有两支队伍。1)主队2)客队。我需要找到主队和客队的记录。我怎样才能回收代码,这样我就不必在两个类中具有相同的函数?
游戏不应该扩展团队,因为游戏不是团队。游戏是团队玩的东西,它是一个完全不同的对象,你所建模的继承方式不应该适用。
class game{
private $homeTeam;
private $awayTeam;
function GetHomeTeam()
{
return $this->homeTeam;
}
function GetAwayTeam()
{
return $this->awayTeam;
}
}
可以使用继承的示例(并继续使用sport域)
class Team
{
function GetSeasonRanking(){...}
}
class SoccerTeam extends Team
{
function GetGoalKeeper(){...}
}
class BaseballTeam extends Team
{
function GetPitchers{...}
}
足球队和棒球队(子类型)都是球队(超级类型),并且都有赛季排名,但是它们必须扩展团队以实现团队所玩游戏的复杂性。