Jump to content

about unset


masterinex

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 ?

Link to comment
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.

Link to comment
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.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

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