我正在用PHP写一个足球经理模拟器,[HARD AlgorithMS!]
我有3个课程:
播放器
class Player {
protected $name;
public function addAttr($name) {
$this->name = $name;
}
}
团队
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();
}
和游戏
class Game {
protected $t1;
protected $t2;
function setTeams($team1,$team2) {
$this->t1 = $team1;
$this->t2 = $team2;
}
function getOpponetPlayersPosition() {
$this->t1->getPlayers();
}
}
和主要脚本
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();
我需要在团队类
中使用 getOpponetsPosition()功能获得游戏中的所有玩家位置但它不会返回我在主脚本中输入的值。 我这样做对吗?这是app im writing的好方法吗?
答案 0 :(得分:4)
你的方法很好,有几点:
class Player {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function addAttr($name) {
$this->name = $name;
}
}
然后
new Player("Lionel Messi");
构造商还确保您不会让玩家/团队空名!您可以更好地控制课程中的内容!
你的getOpponentsPosition函数不正确
public function getOpponetsPosition() {
GAME::getOpponetPlayersPosition();
}
事实上,它甚至不应该在这里,获取其他球队的位置并不是Team
的工作,因为它包含两者。
<强> See this gist for how I would have accomplished your goal. 强>
答案 1 :(得分:3)
不,您正在调用静态函数GAME::getOpponetPlayersPosition();
,因此未定义该函数内的$this
。