PHP>如何将一个Class划分为多个Class?
我有一个非常大的 PHP 类,名为“Player”。
里面有很多函数(近2000行)。实际上,我以这种方式使用这些函数:
$player = new Player(1)
echo $player->getLogin();
echo $player->getStatisticPerception();
echo $player->getWeaponId();
echo $player->attackPlayerId(3,$player->getWeaponId());
我认为将此类划分为多个类可能是一个好主意,但我不知道如何划分。我怎样才能创建类似的东西,例如:
$player = new Player(1);
echo $player->getLogin();
echo $player->statistics->getAttack();
echo $player->stuff->getWeaponId();
echo $player->doAction->attackPlayerId(3, $player->getWeaponId());
如果我认为我必须在这个对象内创建一个对象,但如果我这样做,我将无法访问主“$player”的对象数据(例如,在Stuff中)对象,我无法访问玩家对象的 $level 变量。)
I have a very big PHP class called "Player".
There is a lot of functions inside it(almost 2000 lines). Actually, I use those functions in this way :
$player = new Player(1)
echo $player->getLogin();
echo $player->getStatisticPerception();
echo $player->getWeaponId();
echo $player->attackPlayerId(3,$player->getWeaponId());
I think it could be a good idea to divide this class into multiples classes, but I don't know how. How could I create something like, for example :
$player = new Player(1);
echo $player->getLogin();
echo $player->statistics->getAttack();
echo $player->stuff->getWeaponId();
echo $player->doAction->attackPlayerId(3, $player->getWeaponId());
If think I have to create an object inside this object, but if I do so, i can't access the main "$player"'s object data (for example, in the Stuff Object, I can't access on the $level variable of the Player Object.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以创建多个类,例如
PlayerStatistics
、Weapon
和PlayerActions
并将它们链接到 Player 类...一个示例:类似的东西..它是一个对象组合或聚合,具体取决于对象之间的关系。
希望这有帮助
you can create multiple clases like
PlayerStatistics
,Weapon
andPlayerActions
and link them to the Player Class... an example:something like that... it's an object composition or aggregation, depending on the relation between objects.
Hope this helps
您可以使用类继承
You can use class inheritance
在这样的行中:
您正在访问 Player 类的
statistics
成员。为了使用链接,该变量也必须是一个对象。您可以创建一个单独的统计类,其中包含getAttack
方法。然后在 Player 类构造函数中,将 $this->statistics 初始化为统计类的实例。类似地,对于
stuff
和doAction
,它们需要是对象。尽管我不确定它们是否真的适合单独对象的候选者。In a line like this:
You are accessing the
statistics
member of the Player class. In order to use chaining, that variable must also be an object. You can create a separate Statistics class that includes agetAttack
method. Then in the Player class constructor, initialise$this->statistics
to an instance of the Statistics class.Similarly for
stuff
anddoAction
, they would need to be objects. Although I'm not sure they are really appropriate candidates for separate objects.