我用php写了一个足球经理模拟器,硬AlGORITHMS!
我有三个班:
播放器
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();
}和对策
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()函数在Team类游戏中的所有玩家位置。
但是它不返回我在我的主脚本中输入的值。我做得对吗?这是一个很好的应用程序im写作方法吗?
发布于 2012-05-11 20:41:08
你的方法很好,有几点:
使用构造函数,它们可以使您的生活更轻松:
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的工作去获取其他球队的位置,这将是游戏的,因为它包含了两者。
发布于 2012-05-11 20:36:31
不,您正在调用一个静态函数,GAME::getOpponetPlayersPosition();,因此没有定义函数中的$this。
https://stackoverflow.com/questions/10558239
复制相似问题