Some OOP / Arrays help please...
Posted: Sat Dec 18, 2010 3:51 am
I have created two classes. One is called 'move' and the other 'unit'. To make my example easier to follow, I shall use the much loved pokemon series to explain my dilemma.
Here are the class declarations.
Now I shall instantiate these classes (if that makes sense xD) - I just started OOP yesterday, do mind my ignorance.
Now, let's say I want to populate the $move array with the moves in the unit object (thunderbolt and quick-attack). I can retrieve their attack values from a database:
I now want to create a function that will create instances of the 'move' class to produce:
Here is my dire attempt to do so:
I'm ending up with a multi-dimensional array when I want a linear one like this:
What do I need to do. Do I have to resort to making $move global from within the function and do things that way?
Here are the class declarations.
Code: Select all
new class unit {
var $name, $moves;
public function newUnit($name, $moves) {
$this->name = $name;
$this->moves = $moves;
}
}
new class move {
var $name, $attack;
public function newMove($name, $attack) {
$this->name = $name;
$this->moves = $moves;
}
}
Code: Select all
$unit = array();
$move = array();
$unit[0] = new unit; $unit[0]->newUnit("picachu",array("thunderbolt","quick-attack"));
Now, let's say I want to populate the $move array with the moves in the unit object (thunderbolt and quick-attack). I can retrieve their attack values from a database:
Code: Select all
$thunderboltAttack = 200;
$quick-attackAttack = 40;
Code: Select all
$move[0] = new move; $move[0]->newMove("thunderbolt",200);
$move[1] = new move; $move[1]->newMove("quick-attack",40);
Code: Select all
function createUnits($moves){ //$moves is the array holding the unit's moves
for($i; $i < count($moves); $i++) {
$arr[] =new move;
$arr[count($units) - 1]->name = $moves[0];
$arr[count($units) - 1]->attack = $someAttackData;
}
return $arr;
}
$moves[] = createUnits;
Code: Select all
$move[0] = new move; $move[0]->newMove("thunderbolt",200);
$move[1] = new move; $move[1]->newMove("quick-attack",40);
What do I need to do. Do I have to resort to making $move global from within the function and do things that way?