Why UNSET and NULL work differently

I have this code for passing heavy variables among different classes. The goal is that there should be no duplication of values โ€‹โ€‹in the memory, so the variables are passed by reference instead of the value.

I have this sample here. It works great, except for one way. To make sure that the value is not duplicated in memory, I change the value or delete it to make sure.

Then I realized that UNSETing a variable has a different effect and making it NULL has a different effect.

If I UNSET the source variable, I still get the value from the reference variable. If I make the source variable NULL, it will not return anything.

Here is the code:

<?php class a { private $req; public function store_request(&$value) { $this->req = &$value; } public function get_request() { return $this->req; } } class b { private $json; private $obj; public function init_req(&$request) { $this->obj = new a; $this->obj->store_request($request); } public function get_req() { return $this->obj->get_request(); } } $locvar = 'i am here'; $b = new b; $b->init_req($locvar); $locvar = 'now here'; ## This will not result empty echo from 'echo $b->get_req();' //unset($locvar); ## This will result in empty echo from 'echo $b->get_req();' //$locvar = null; echo $b->get_req(); ?> 

UNSET and NULL lines are numbered. If you are trying to run the code, do not combine one line at a time (I know this is stupid advice here, but still :))

Can anyone tell what is going on inside?

+1
source share
1 answer
  • unset linking a link to a value removes the link to this value, the value itself and other links pointing to it are untouched.
  • Assigning something to a link overwrites the value that the link refers to, and therefore the value of all other links pointing to it.
  • You do not need to micro-level memory in PHP. PHP will not copy the value in memory when passing values โ€‹โ€‹around. It uses a copy-to-write strategy that only allocates new memory when absolutely necessary. PHP references are a logical operation for creating a specific behavior; they are not memory management tools or C pointers.
+3
source

All Articles