Jump to content

Problem with function and variables


timjahn
Go to solution Solved by requinix,

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
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.

Edited by Psycho
Link to comment
Share on other sites

  • Solution

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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.