Im writing a football manager simulator with php, [ HARD AlGORITHMS !]
i have 3 class :
Player
class Player {
protected $name;
public function addAttr($name) {
$this->name = $name;
}
}
Team
class Team {
protected $name;
protected $players = array();
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function addPlayer($player) {
$this->players[] = $player;
}
public function getPlayers() {
print_r($this->players);
}
public function getOpponetsPosition() {
GAME::getOpponetPlayersPosition();
}
and Game
class Game {
protected $t1;
protected $t2;
function setTeams($team1,$team2) {
$this->t1 = $team1;
$this->t2 = $team2;
}
function getOpponetPlayersPosition() {
$this->t1->getPlayers();
}
}
and main script
require_once 'classes/CPlayer.php';
require_once 'classes/CTeam.php';
require_once 'classes/CGame.php';
$game = new Game;
$team1 = new Team;
$team1->setName("PO-1");
$team2 = new Team;
$team2->setName("PO-2");
$p1 = new Player;
$p2 = new Player;
$p1->addAttr("payam babaiy");
$p2->addAttr("parsa babaiy");
$team1->addPlayer($p1);
$team2->addplayer($p2);
$game->setTeams($team1,$team2);
$team1->getOpponetsPosition();
I Need to get all player positions in game with getOpponetsPosition() function in Team class
but it doesnt return values which i inputed in my main script.
am i doing this right ? is this a good approach for app im writing ?
Your approach is good, a few points:
Use constructors, they can make your life easier:
And then
Constructors also ensure you don’t get players/teams with empty names! You get better control over what gets in your classes!
Don’t mix static and normal code
Your getOpponentsPosition function is not correct
In fact, it shouldn’t even be here, it’s not the
Team‘s job to fetch the other team’s positions, that would be the game’s, since it contains both.See this gist for how I would have accomplished your goal.