php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #42617 Destructor not getting called when reference is overwritten
Submitted: 2007-09-10 19:22 UTC Modified: 2007-11-12 11:47 UTC
Votes:2
Avg. Score:5.0 ± 0.0
Reproduced:2 of 2 (100.0%)
Same Version:1 (50.0%)
Same OS:1 (50.0%)
From: garethinwales at gmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.3CVS-2007-10-22 OS: CentOS 5
Private report: No CVE-ID: None
 [2007-09-10 19:22 UTC] garethinwales at gmail dot com
Description:
------------
When the class member $one of class two is replaced by a new object instance, the destructor is not called.

This seems incorrect as the previous object is being remove with no references and therefore the destructor should be called.

you can get what I'd assume to be the currect fucntionality by uncommenting the line // $this->one=null;

Many thanks
Gareth Jones

Reproduce code:
---------------
class one {
	function __construct() {
		echo "__construct() one\n";
	}
	function __destruct() {
		echo "__destruct() one\n";
	}
}
class two {
	public $one = null;
	function __construct() {
		echo "__construct() two\n";
		$this->one = new one();
		// $this->one=null;
		$this->one = new one();
	}
	function __destruct() {
		echo "__destruct() two\n";
	}
}
$two = new two();

Expected result:
----------------
__construct() two
__construct() one
__destruct() one
__construct() one
__destruct() two
__destruct() one


Actual result:
--------------
__construct() two
__construct() one
__construct() one
__destruct() one
__destruct() two
__destruct() one

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-10-22 11:22 UTC] jani@php.net
Simplified code:

<?php
class one {
  function __construct() {
    echo "__construct()\n";
  }
  function __destruct() {
    echo "__destruct()\n";
  }
}
$a = new one;
// $a = null;
$a = new one;
?>

Outputs:
__construct()
__construct()
__destruct()
__destruct()

And when the $a = null; line is uncommented:
__construct()
__destruct()
__construct()
__destruct()


 [2007-11-12 11:47 UTC] colder@php.net
I can't reproduce it with the following code:

<?php
class A {
    public $name = '';
    
    public function __construct($name) {
        $this->name = $name;
        echo "__construct($name)\n";
    }
    public function __destruct() {
        echo "__destruct($this->name)\n";
    }   
}   

$a = new A('one');
$a = new A('two');
echo "end\n";
?>

The result is :
__construct(one)
__construct(two)
__destruct(one)
end
__destruct(two)

which seems expected as 
1) new A('two'); is evaluated, instantiating the class, 
2) assigned to $a, destroying the old value.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Fri Aug 01 11:00:02 2025 UTC