-1

好的,我知道。我知道......这可能是一个简单的。但是,我对 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.) 客队。我需要找到主队和客队的记录。如何回收代码,以便我不必在两个类中具有相同的功能?

4

1 回答 1

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(子类型)都是球队(超类型)并且有一个赛季排名,但是他们必须扩展球队以实现球队比赛的复杂性。

于 2013-01-19T22:52:24.093 回答