1

I have this code to pass heavy variables among different classes. The objective is there should not be any duplication of values in Memory so the variables are passed by referance instead of by value.

I have this sample here. It works fine except in one way. Just to make sure that the value is not duplicated in Memory I modify the value or delete the value to make sure.

Then I figured that UNSETing the variable has different effect and making it NULL has different effect.

If I UNSET the original variable then still I get the value from referenced variable. If I make the original variable as NULL it returns nothing.

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 commented. If you are trying to run the code uncommet one line at a time (I know this is dumb advice here but still :) )

Can anyone tell here what is happening internally??

hakre
  • 193,403
  • 52
  • 435
  • 836
user1402647
  • 480
  • 4
  • 9

1 Answers1

3
  1. unsetting a reference to a value removes the reference to that value, the value itself and other references pointing to it are untouched.
  2. Assigning something to a reference overwrites the value that reference is pointing to, and thereby the value of all other references that point to it.
  3. You do not need to micromanage memory in PHP. PHP will not copy the value in memory when passing values around. It uses a copy-on-write strategy which only allocates new memory when absolutely necessary. References in PHP are a logical operation to produce certain behavior, they are not memory management tools or C pointers.
deceze
  • 510,633
  • 85
  • 743
  • 889