[分享] PHP GC 機制

看板PHP作者 (Ricky)時間12年前 (2013/06/03 18:52), 編輯推噓0(002)
留言2則, 2人參與, 最新討論串1/2 (看更多)
題外話: 搞了好久終於註冊好 PTT 了。 ====================================== 前陣子看到某篇文章提到,要回收物件時, 使用 $obj = null 會馬上回收,unset($obj) 則會比較慢。 在解答之前,先來玩個小遊戲。 <?php class test { public function __destruct() { echo "object of test is dead\n"; } } $test = new test(); $test = null; die("program is end\n"); 執行結果 object of test is dead program is end 很符合結果 $test = null 先執行 GC (destruct) 接著 die output =================== <?php class test { protected $me; public function __contruct() { $this-> me = $this; } public function __destruct() { echo "object of test is dead\n"; } } $test = new test(); unset($test); die("program is end\n"); 執行結果 program is end object of test is dead unset 沒有進行 GC,一直到程式結束後,才開始進行 GC。 疑 unset 沒有進行 GC ??!! 好玩的事情發生了,難道真的是 unset 是看心情 GC 的?? 其實上面的範例即使改成 $test = null; 執行結果也是一樣的。 這邊就先賣個關子,明天再來解答為什麼會有這個結果,以及該怎麼避免這樣的問題。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.130.136.115

06/03 21:08, , 1F
這不能稱GC吧?這是PHP直譯類別物件的解構方式順序而已
06/03 21:08, 1F

06/03 23:29, , 2F
我兩種跑出來的結果都跟第一種一樣
06/03 23:29, 2F
文章代碼(AID): #1Hh7LJYj (PHP)
討論串 (同標題文章)
以下文章回應了本文
完整討論串 (本文為第 1 之 2 篇):
0
2
文章代碼(AID): #1Hh7LJYj (PHP)