PHP variable scope and IFs
I have roughtly something similar to this:
function get_gender ($gid){
$return= '';
...some code ..
if ($male !== 0 && $female !== 0){
$return = 'mixed';
}else if ($male !== 0 && $female == 0){
$return = 'male';
}
return $return;
}
I know for a fact that one of the condition is met, so i assumed the $return variable woul开发者_运维百科d be updated. Though it always comes back empty. Is this a problem of scope ?
In your code, if $male
is zero, $female
is never checked, and neither assignment is run, leaving $return
empty.
No, it's a debugging problem. Scope has nothing to do here since it doesn't change (at least not in the code you provided).
Try this:
if ($male !== 0 && $female !== 0){
$return = 'mixed';
echo 'Return: ' . $return;
}else if ($male !== 0 && $female == 0){
$return = 'male';
echo 'Return: ' . $return;
} else {
echo 'None of the conditions met';
}
Besides, don't you want booleans for this (true, false) instead of explicit integer checking?
No scope should not be a problem here.
More than likely your problem lies in your conditions. Particularly the use of strict equality (i.e. !==
).
nope, this isn't a scope-problem. your variables must be set wrong, so the conditions arn't met. maybe thats because the result should be a female (i can't see an option for that), or it's because you're using explicit type-sensitive conditions(maybe your variables contain strings ander - try to make ===
to ==
and !==
to ==
and see if something changes)
to proof this, try to add another else{ }
and set $return
to "oh noez" (or something else).
精彩评论