Here is my little script, and from writing it I’ve learned that I’ve no idea how PHP handles variables…
<?php
$var = 1;
echo "Variable is set to $var <br />";
if (!foo()) echo "Goodbye";
function foo()
{
echo "Function should echo value again: ";
if ($var == 1)
{
echo "\$var = 1 <br />";
return true;
}
if ($var == 2)
{
echo "\$var = 0 <br />";
return false;
}
}
?>
So, here is how I thought this script would be interpreted:
-
The statement
if (!foo)would runfoo(). If the function returnedfalse, it would also echo “Goodbye” at the end. -
The function
foo()would check whether$var == 1or2(without being strict about datatype). If 1 it would echo “Function should echo value again: 1”, and if 2, it would echo the same but with the number 2.
For some reason both if statements inside foo() are being passed over (I know this because if I change the first if statement to if ($var != 1), it passes as true, even if I declared $var = 1.
What’s happening here? I thought I had all this down, now I feel like I just went backwards :/
The function doesn’t know what
$varis. You’d have to pass it in, or make it global:Or
By the way, it’s almost always better to avoid global variables. I would encourage you to go the latter route and pass the value into the function body instead.