dsio68964998 2019-01-27 18:50
浏览 48

理解OOP的概念[关闭]

Apologies for the potentially super simple question. I am trying to understand OOP. I have gone through tutorials but many of them are hyper simplified and by giving myself a 'real' project I am hitting obstacles most tutorials don't seem to cover. Heres a scenario I kind of wish to understand:

If I was making a very basic sports game (think Fifa) I currently have 3 objects:

  • Object of Pitch
  • Object of Team
  • Object of Player

I am hitting my first wall of understanding because I don't want player to simply be an extension of team. After all in real life we would all be objects of human with an attribute that tells us which team we belong to before we are a sub object of a team.

What is the best practise for this?

Should I be:

  1. Creating the objects of player and then adding each object to an array which is stored against the team object? This is how I would do it procedurally.
  2. Storing the team against the player.
  3. Storing the player against the team.
  4. Extending player by team (I want to avoid this unless its actually the done thing)

This is just a brain exercise right now so I don't really have code but

$team1 = new teamObject('red');

$player1 = new players('John'); 
$team1->addToTeam($player1); 

This strikes me as it wouldn't work because in the teamObject Class I wouldn't be able to call any of the Player classes function on the passed player function?

  • 写回答

2条回答 默认 最新

  • dtz8044 2019-01-27 18:55
    关注

    This generally makes sense to me:

    $team1 = new teamObject('red');
    $player1 = new players('John'); 
    $team1->addToTeam($player1); 
    

    Although typically it would probably look more like this (but it's really the same thing):

    $team1 = new Team('red');
    $player1 = new Player('John'); 
    $team1->addPlayer($player1); 
    

    This strikes me as it wouldn't work because in the teamObject Class I wouldn't be able to call any of the Player classes function on the passed player function?

    You certainly can call Player functions, because after adding the player to the team, the team will have a reference to the player(s). It can simply call player functions via that reference. A function in the team might use:

    $this->players[0]->pretendToBeHurt();
    

    You absolutely don't want to extend Team in this scenario.

    评论

报告相同问题?

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000