Jump to content
Sign in to follow this  
masterinex

about unset

Recommended Posts



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

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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.

  • Like 1

Share this post


Link to post
Share on other sites

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.

Sign in to follow this  

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