Page 1 of 1

Little question

Posted: Wed Aug 23, 2006 12:43 am
by Flamie
Hey guys, long time :)
I'm having a little problem, I'll do my best to describe it:

so I have a player class, with one of its data is an array of strings called msgs.
I have a game class wich creates an object $player of the above class.
Now, I have a 3rd class called Grenade, its constructor takes a $player as a paramter.

now:
Game calls $player->UseWeapon($weaponid);
UseWeapon gets the name of the weapon (Grenade in this case) as $name.
then does the following line:
$weapon = new $name($this); //it passes itself to the other class.
Player has a functioncalled AddMessage($string); which adds a string to the array mentioned above.
Now, when I was on a PHP5 server, everything worked fine. In the Grenade class I could do $player->AddMessage("something here"); and it would add that message to the SAME object as the one instantiated in my Game class.

Now I'm on a PHP4 server, and when I do $player->AddMessage("something here"); in my Grenade class, it calls the right function and all, but it seems it modifies a "copy" of the player class and not the actual version of it.

I tried changing the constructor of my grenade class from:
function Grenade($player) to function Grenade(&$player) but it didnt help.

Any help will be greatly appreciated. I'm not sure if I was clear with my explanation as it is a bit complicated.
Regards,
Marc

Posted: Wed Aug 23, 2006 1:35 am
by RobertGonzalez
It sounds like you are using an object reference. Post some code so we can see for sure.

Posted: Wed Aug 23, 2006 2:49 am
by Christopher
In PHP4 you need to do both of the following.

Code: Select all

// use references when creating instances
$weapon =& new $name($this);

// pass objects by reference
function Grenade(&$player) {

     // and assign by reference to a property
     $this->player =& $player;
}
If you are not consistent with using references you will get copies of the object and not the original instance.

Posted: Wed Aug 23, 2006 6:47 am
by Ollie Saunders
PHP4 is teh sux for this.
Use PHP5 if you can. It will make you and everyone around you much happier and shine from within (they don't tell you that in the manual).

Posted: Thu Aug 24, 2006 1:47 am
by Flamie
arborint wrote:In PHP4 you need to do both of the following.

Code: Select all

// use references when creating instances
$weapon =& new $name($this);

// pass objects by reference
function Grenade(&$player) {

     // and assign by reference to a property
     $this->player =& $player;
}
If you are not consistent with using references you will get copies of the object and not the original instance.
Thank you this helped me a bunch :)