好的,我知道。我知道......这个可能很容易。但是,我对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;
}
由于标题为“游戏”的类是标题为“团队”的类的扩展,游戏类不能访问团队类范围内的所有功能吗?在团队类中编写的getTeamSeasonRecord()函数将查找任何给定团队的记录。但是,对于游戏类,有两个团队。 1.)主队和2.)客队。我需要找到主队和客队的记录。如何回收代码,以便我不必在两个类中都具有相同的功能?
答案 0 :(得分:0)
游戏不应该扩展团队,因为游戏不是团队。游戏是由团队扮演的东西,它完全是一个不同的对象,并且你建模的方式的继承不应该适用。
class game{
private $homeTeam;
private $awayTeam;
function GetHomeTeam()
{
return $this->homeTeam;
}
function GetAwayTeam()
{
return $this->awayTeam;
}
}
可能使用继承(并继续使用运动领域)的示例
class Team
{
function GetSeasonRanking(){...}
}
class SoccerTeam extends Team
{
function GetGoalKeeper(){...}
}
class BaseballTeam extends Team
{
function GetPitchers{...}
}
SoccerTeam和BaseballTeam(子类型)都是球队(超级球队)并且有赛季排名,但他们必须扩展球队以实现球队比赛的复杂性。