Jump to content

Problem with function and variables


timjahn

Recommended Posts

Hey:) I have a question. It may sound dumb, but I can't figure out the problem.

What I have:

<html><body>
<?php
$x=5;
$z=6;
$y=$x+$z;

function myTest()
{
global $x, $z, $y;
echo $x . " " . $z . " " . $y . " ";
$x++;
$z++;
}
myTest();
myTest();
echo "<br>";
echo $x . " " . $z . " " . $y;
?>
</body>
</html>

 

 

Now my problem is that I don't know why the value of y doesn't change. x and z are changing fine, but y isn't.

 

Thanks:)

Tim

 

Link to comment
https://forums.phpfreaks.com/topic/278046-problem-with-function-and-variables/
Share on other sites

What are you getting output and what are you expecting to be output?

 

EDIT: I ran that code and what I received was

 

Output from first call to myTest(): X = 5, Z = 6, Y = 11
Output from first call to myTest(): X = 6, Z = 7, Y = 11
Output after second call to myTest(): X = 7, Z = 8, Y = 11

 

 

Which is correct. No where in that code is the value of $y being modified.

If you say "$y=$x+$z" you are not defining a math equation but are doing an assignment: take $x, add $z, and save that to $y. If $x or $z changes that won't affect $y because you're changing them after you did the addition and assignment.

If you say "$y=$x+$z" you are not defining a math equation but are doing an assignment: take $x, add $z, and save that to $y. If $x or $z changes that won't affect $y because you're changing them after you did the addition and assignment.

 

I changed it to that..:

<html>
<body>
<?php
$x=5;
$z=6;
$y=$x+$z;


function myTest()
{
global $x, $z, $y;
echo $x . " " . $z . " " . $y . " ";
$x++;
$z++;
$y=$x+$z;
}
myTest();
myTest();
echo "<br>";
echo $x . " " . $z . " " . $y;
?>
</body>
</html>

..and it is working:) thank you so much;)

Thanks to you too, psycho

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.