Jump to content

[SOLVED] OOP PHP 4-5 Problem


V34

Recommended Posts

It's actually the same problem as last time, but this time I got more specific with my problem.

It seems like the Health variable don't want to change of some reason.

 

I'm still using PHP 4.

<?php
class Person {
  var $health = 100;

  function attack($perAtt) {
   if ($man->health > 0 && $woman->health > 0) {
   $perAtt->health = $perAtt->health - 25;
   }
  }

}

$man = new Person();
$woman = new Person();

while ($man->health > 0 && $woman->health > 0) {
$man->attack($woman);
$woman->attack($man);
echo "$man->health | $woman->health<hr>";
}

echo $man->health." || ".$woman->health;

?> 

 

It echo's 100 | 100 all the time, but if I change my PHP version from 4 to 5 there's no problem at all.

Now this is not a solution. I want to know how I change the variable, thanks.

 

- Jesper Eiby

Link to comment
https://forums.phpfreaks.com/topic/53302-solved-oop-php-4-5-problem/
Share on other sites

<?php
class Person {
		var $health = 100;

		function attack($perAtt) {
		 if ($this->health > 0 && $perAtt->health > 0) {
		  $perAtt->health = $perAtt->health - 25;
		 }
		}

}

$man = new Person();
$woman = new Person();

while ($man->health > 0 && $woman->health > 0) {
$man->attack($woman);
$woman->attack($man);
echo $man->health." | ".$woman->health."<hr>";
}

echo $man->health." || ".$woman->health;

?>

 

My bad, but still this improvement didn't seem to work.

<?php
class Person {
var $health = 100;

function attack($perAtt) {
	if ($this->health > 0 && $perAtt->health > 0) {
		$perAtt->health = $perAtt->health - 25;
	}
}
}

$man = &new Person();
$woman = &new Person();

while ($man->health > 0 && $woman->health > 0) {
$man->attack($woman);
$woman->attack($man);
echo $man->health." | ".$woman->health."<hr>";
}
echo $man->health." || ".$woman->health;
?>

 

It outputs this on php5:

 

75 | 75

50 | 50

25 | 25

25 | 0

25 || 0

 

I don't see any reason why it should output anything different on php4.

The above post should work. It's basic stuff, actually, but I've been off php4 for so long that I overlooked it. php4 makes copies of objects whedn you pass them, so you have to pass by reference to avoid that a copy is made (to avoid $health being set to 100 every time you attack()).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.