php - Destroying embeded objects when destroying the main object -


i'd destroy object , intern objects in it. why example below not working:

<?php class {     public $elt = 'hello world!!';     public function __destruct()     {         var_dump('i: destroyed');     } }  class {     public $val1=1;     public $val2=2;     public $val3=3;     public $val4=4;     public $i;     public function __construct($i)     {         $this->i = $i;     }     public function __destruct()     {         var_dump('a destroyed');         unset($this->i);     } }  $i = new i(); $a = new a($i); unset($a); var_dump($i); 

output:

  string(11) "a destroyed"   object(i)#1 (1) { ["elt"]=> string(13) "hello world!!" }   string(12) "i: destroyed" 

how come didn't notice undefined variable: i? , how come message of destructor of class displayed after var_dump of $i?

update

the thing have main object, object has purge/refresh nested objects @ end of each iteration of loop.

let's talk 4 lines of code:

$i = new i(); $a = new a($i); unset($a); var_dump($i); 

the first line creates object of type i , stores reference in variable $i (php objects assigned references, need use operator clone create copy).

the second line passes $i constructor of class a , creates reference same object, stored in $a->$i.

the third line destroys object of type a; removes second reference object of type i not affect first one; variable $i still holds it.

the fourth line dumps content of variable $i never unset. object of type i created on first line.

if want destroy object of type i when object of type a destroyed make sure there no other reference it. can accomplished either creating object of type i in constructor of class a or removing references $i after passed constructor of class a. adding unset($i); after $a = new a($i); job.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -