I was trying to understand how does PHP handle objects under the hood. so i ran this small test script This basically
- creates a new object,
- save it to an array,
- return the array element -containing the object- to be saved in other variable.
- 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 :)
$f->repository[0]tonull, all you've done is unset that particular reference. See this comment