masterinex Posted August 24, 2017 Share Posted August 24, 2017 <?php $bar = 0 ; function foo(&$bar) { $bar++; echo "Before unset: $bar, "; unset($bar); //echo " unset: $bar, "; $bar = 23; echo "after unset : $bar \n"; } function foo2() { //static $bar; $bar++; echo "Before unset: $bar, "; unset($bar); //echo " unset: $bar, "; $bar = 23; echo "after unset : $bar \n"; } foo($bar); foo($bar); foo($bar); ?> when i run the code i am getting : Before unset 1, after unset:23 Before unset 2, after unset 23 Before unset 3, after unset 24 ; should it not be : Before unset 1, after unset:23 Before unset 24, after unset:23 Before unset 24, after unset:23 because after the first time the function foo is called , the value of bar is 23 and when it enters the foo the second time its value will be incremented from 23 +1 which is 24 which yields the line Before unset 24, after unset:23 is my logic correct ? Quote Link to comment Share on other sites More sharing options...
requinix Posted August 24, 2017 Share Posted August 24, 2017 Not quite. unset($bar) in the function only unsets the $bar variable in the function. The $bar from outside the function still exists. You named the two variables the same but that doesn't make them actually the same. And no, you cannot unset the outside $bar. All you can do with the reference is change its value. Quote Link to comment Share on other sites More sharing options...
Jacques1 Posted August 24, 2017 Share Posted August 24, 2017 I don't think you understand what unset() does. When you unset() the $bar variable in your function, then you completely destroy the reference to the outer $bar variable -- that's the whole point of unset(). There's no longer any connection between the two. Setting a new value to $bar is now purely local and doesn't affect the global $bar variable. I think this will become a lot clearer if you use two different names for the variables. 1 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.