Momen Zalabany
Momen Zalabany

Reputation: 9007

how does php handle objects in memory

I was trying to understand how does PHP handle objects under the hood. so i ran this small test script This basically

  1. creates a new object,
  2. save it to an array,
  3. return the array element -containing the object- to be saved in other variable.
  4. manipulate object and see if both variable and array objects will be same.

class a
{
    public $a=0;
}
class factory
{
    public $repository=[];

    function make($name){
        $this->repository[]= new $name;
        return end($this->repository);
    }
}

$f = new factory;
$a = $f->make('a'); //a Object([a]=>0);

$a->a = 6;
print_r($f->repository);  //a Object([a] => 6)
print_r($a);        //a Object([a] => 6)

$f->repository[0]->a = 9;

print_r($f->repository);  //a Object([a] => 9)
print_r($a);        //a Object([a] => 9) !

$f->repository[0] = null;
print_r($a);        //a Object([a] => 9) still. SO WHERE DOES THE OBJECT LIVES ?

The Result was that both $a and $this->repository[0] kept sync, any change in state of $a is reflected on repository array element and vise versa.

Yet if i unset $this->repository[0] $a is unaffected (although repo array was the source that created the object in first place).

I feal like i'm missing the basics here, so can some one elaborate how does php handle objects in memory, what happens when you pass object to a variable or a function ?

Note:

i'm aware of object Clone/destruction, my question is not a How to clone or copy question, its about How Does object move around in code, where does it lives, and what am i actually assigning when i assign an object to a variable ?

thanks :)

Upvotes: 1

Views: 129

Answers (2)

mseifert
mseifert

Reputation: 5670

As Barmar has said, they are pointers to the same object. My understanding is that when all pointers to that object ($a and this->repository[0]) have been destroyed (set to null, go out of scope, explicitly unset), then the object is no longer accessible - the internal object pointer counter will be 0. When php cleanup happens, the object's memory will (hopefully) be freed. However, I am not privy to the internals - this is just from testing I have done - similar to yours and with tracking memory usage.

Upvotes: 0

Barmar
Barmar

Reputation: 780724

$a and this->repository[0] are both pointers to the same object. Changing the contents of the object is visible through both references. But reassigning either variable changes what that variable refers to, but doesn't change the object that it used to point to.

Upvotes: 1

Related Questions