PHP > How to divide a Class into multiple Class?

1.2k views Asked by At

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.)

3

There are 3 answers

0
pleasedontbelong On BEST ANSWER

you can create multiple clases like PlayerStatistics, Weapon and PlayerActions and link them to the Player Class... an example:

class Player{
    private Statistics; 
    private Weapon;

    function __construct(){
        $this->Statistics = new Statistics($this);
        $this->Weapon = new Weapon($this);
    }

    function getAttack(){
        return $this->Statistics->getAttack();
    }
}

class Statistics{
    private Player;
    function __construct($_player){
         $this->Player = $_player;
    }
}

something like that... it's an object composition or aggregation, depending on the relation between objects.

Hope this helps

0
Irwan On

You can use class inheritance

Class Player {
  protected $level;
  public $stuff;
  function __construct() {
    $this->stuff = new Stuff();
  }
}

Class Stuff extends Player {
  function getWeaponId() {
    // You can access Player's $level here using $this->level
  }
}
0
DisgruntledGoat On

In a line like this:

echo $player->statistics->getAttack();

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 a getAttack method. Then in the Player class constructor, initialise $this->statistics to an instance of the Statistics class.

Similarly for stuff and doAction, they would need to be objects. Although I'm not sure they are really appropriate candidates for separate objects.