Question

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

Was it helpful?

Solution

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

OTHER TIPS

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
  }
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top