I'm confused now and don't understand what is best to use.

$a = null;

or

unset($a);

Tell me more than this or that design is different.

  • one
    It's strange to compare this, because the assignment of null says: "Dude, the variable is empty!", Whereas unset hints: "Smoked stol? There is no such variable." - user207618 8:40 pm

1 answer 1

There is a difference between these two operations.

 <?php $fst = 'hello'; $snd = 'world'; $fst = null; unset($snd); echo $fst; // null echo $snd; // Notice: Undefined variable: snd 

Assigning a variable to null , a variable with the value null left in the symbol table of your script. Removing a variable with the unset() construct unset() it from the symbol table.

Correctly delete the unset() variable. By assigning null you do not delete the variable, but assign it the value null - yes isset() will show false , but the variable exists. Moreover, you will find a few more subtle points in the case of variable objects and array elements. unset() will remove both the value and the variable from the symbol table. If you want to delete a variable, delete unset() .

  • I heard that unset works when the php garbage collector arrives (that is, not immediately, not when unset is called), but with null you can immediately clear the variable - MaximPro
  • I will not lie, I did not examine the source code on this topic, but it would be reasonable to simply add a reference to the selected object when assigning the variable to null and then collect it regularly with the same garbage collector. Dorogova, then clean up each variable separately, if within a few seconds it will be possible to release the entire heap in a crowd (maybe even without launching the collector). - cheops
  • yes, by the way, the difference will be only if there is an assignment by reference $a = "10"; $b = &$a; $a = null; $a = "10"; $b = &$a; $a = null; - as a result, everything is in null and if you apply instead of null, unset($a) , then the $b variable will exist with a value of 10 ... I just don’t know how to do it ... completely confused, somebody would explain to the shelves, would be grateful - MaximPro
  • @MaximPro Correctly delete the unset () variable. In the case of the link, everything is correct, instead of null you can substitute the value 10 and get the same result and $ a, and $ b will get the same value. By assigning null you do not delete the variable, but assign it the value null - yes isset () will show false, but the variable exists. Moreover, you will find a few more subtle points in the case of variable objects and array elements. unset () will remove both the value and the variable from the symbol table. If you want to delete a variable, delete unset (). - cheops
  • hmm ... ok ... i will do what you said - MaximPro