php function return value unexpected
I need help understanding this PHP code example:
$bar = "outside";
function foo($bar) {
$bar = "inside";
return $bar;
}
$bar = foo($bar);
echo $bar
I predicted $bar would echo "outside", but it echoed "inside" and I don't see why. $bar initially has the value "outside" (defined as a global). Then the function foo is called (right after it's defined), and takes a parameter, which also happens to be called $bar. $bar was given the value "outside", so the value "outside" is passed into foo. Then we have the statement $bar = "inside", which doesn't make sense to me, because it seems to mean "outside" = "inside", and how can you assign a string to another string? Then the function returns $bar, which I think should have the value "outside" since that's what was passed to foo. How it acquired the value "inside" I can't开发者_StackOverflow社区 figure out.
Edit: My question isn't about variable scope. What I'm wondering is why the parameter value isn't being passed to the function on line 3, giving the nonsensical statement "outside" = "inside". Based on the answers I've gotten, I can only assume it's because such a statement is illegal in PHP (and probably all other languages), so the interpreter simply doesn't do this (despite the fact that the interpreter's normal behavior is to substitute parameters wherever they occur in the function body).
Thank you
Your line $bar = "inside";
is re-assigning the value of $bar
. So, no matter what value you pass in, $bar
gets assigned the value "inside"
.
Well, I'm no PHP expert but I've worked with a few other languages so let me take a stab:
When the function begins execution the variable $bar is local to the function (you're not referencing the global $bar on line 3). You set this local variable to "inside" and return it. The global $bar is then set to that return value, "inside".
You can see this work if you change the function declaration to:
function foo($bid) {
$bid = "inside";
return $bid;
}
based on the comments you've been posting on other questions I wanted to add something:
When you see "$bid" somewhere in code what happens is not variable substitution, but variable evaluation. In the case of the equal sign being on the right side of this "evaluation" the compiler knows "don't evaluate, set". Whereas when the equal sign is on the left side of the variable then it's evaluated. The compiler knows the function differently when the variable is on the left or right side of the equal sign.
1:
$bar = "outside";
function foo($bar) {
$bar = "inside";
return $bar;
}
$bar = foo($bar);
echo $bar // **echo's inside**
2:
$bar = "outside";
function foo($bar) {
GLOBAL $bar;
$bar = "inside";
return $bar;
}
$bar = foo($bar);
echo $bar // **echo's inside**
3:
$bar = "outside";
function foo($bar) {
$bar = "inside";
GLOBAL $bar;
return $bar;
}
$bar = foo($bar);
echo $bar // **echo's outside**
精彩评论