Okay, I know. I know… this one is probably an easy one. But, I’m very new to OOP and want to learn how to recycle my code more efficiently.
I have a class in php, and then another class that extends a previous class like so
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;
}
Since the class titled “game” is an extension of the class titled “team,” can’t the game class access all of the functions within the scope of the team class? The getTeamSeasonRecord() function that is written in the team class will find the record of any given team. But, for the game class, there are two teams. 1.) the home team and 2.) the away team. I need to find the records of both the home team and the away team. How can I recycle the code so that I don’t have to have the same function in both classes?
Game should not extend team because a game is not a team. A game is something played by teams, its a different object entirely and inheritance in the way you have modelled should not apply.
An example of where inheritance could possibly be used (and continuing with the sporting domain)
SoccerTeam and BaseballTeam (subtypes) are both teams (supertype) and have a season ranking however they must extend team to implement the intricacies of the game the team plays.