Some OOP / Arrays help please...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
parino_esquilado
Forum Newbie
Posts: 13
Joined: Wed Apr 22, 2009 12:22 pm

Some OOP / Arrays help please...

Post by parino_esquilado »

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.

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

}
Now I shall instantiate these classes (if that makes sense xD) - I just started OOP yesterday, do mind my ignorance.

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;

I now want to create a function that will create instances of the 'move' class to produce:

Code: Select all


$move[0] = new move; $move[0]->newMove("thunderbolt",200);
$move[1] = new move; $move[1]->newMove("quick-attack",40);

Here is my dire attempt to do so:

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;

I'm ending up with a multi-dimensional array when I want a linear one like this:

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?
Post Reply