Php Destruct Called Twice

The code below shows that destruct () is called twice. I would like to know why?

class A {
    function hi(){ echo 'hi'; }
    function __destruct(){
        echo 'destroy';
    }
}
class B{
    public $this_ = '';
    function __construct(){
        $this->this_ = new A;
    }
    function __call($method, $params) {
          return call_user_func_array(array($this->this_, $method), $params);
    }
}

$b = new B;
$b->__destruct();

output:

destroydestroy

EDIT

Both zneak and TomcatExodus are correct. If I just:

[..code..]
$b = new B;
$b->__destruct();
print 'end of script';

The output will display:

destroyend of scriptdestroy
+3
source share
4 answers

Invoke destruct does not destroy the object. You call it using __destruct()for the first time, and then when the PHP script exits, it calls it again when you clear it.

If you want to destroy the object before the script completes, unset()it is. You should see only one call of destruction.


, B A. B __call() A, __destruct() B __destruct() A; B , .

+13

B __destruct, __call ( , - echo "calling $method" __call), A .

__destruct : , . , script, A , __destruct .

B, unset($b).

+10

destructor - , . , construct, methods destruct. destruct , variables . destruct , unset($Object) . , , , .

, , , , destruct . ! unset() PHP .

( delete:)) ++, , , . , . , , TWICE .

++! GC ( ):)

--- RANT OVER ---

+2

; , . , .

$b->__destruct() $b->this_ , $b .

script, Zend Engine , , , , , .. $b, $b->this_ Engine .

, $b, - A.

There is no hindrance to destroying an object manually, and it frees up its resources (if the object is not shared, and then the GC will not destroy it, if there are no more links on it, in PHP there are no weak links).

GC working example: http://codepad.org/7JDBoOKY

Objects are destroyed before the code completes. If this were not so, then the output order would be inverted.

0
source

Source: https://habr.com/ru/post/1796433/


All Articles