#39868 [Opn->Fbk]: Destructor is called allthought constructor is never called

From: Date: Mon, 18 Dec 2006 14:46:29 +0000
Subject: #39868 [Opn->Fbk]: Destructor is called allthought constructor is never called
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-106495@lists.php.net to get a copy of this message
ID: 39868 Updated by: tony2001@php.net Reported By: jb at ez dot no -Status: Open +Status: Feedback -Bug Type: *General Issues +Bug Type: Unknown/Other Function Operating System: Kubuntu 6.10 PHP Version: 5.2.0 New Comment: I don't see anything wrong here. With "$b = new Child(); $a = new Master( $b );" the second line does not get executed, of course you won't see any of Master methods called. But "$a = new Master( new Child() );" is totally different case - Master::__construct() is called, you don't see the output because the exception is thrown just before you print it. Previous Comments: ------------------------------------------------------------------------ [2006-12-18 14:31:19] jb at ez dot no Description: ------------ It is possible for PHP to call the __destruct() on an object allthough __construct() was never called. This seems to happen when having nested object creations and the inner one throws and exception in the constructor. The attached reproducable code shows the problem: Child::__construct() [Child] Master::__destruct() [Master] If the last line is changed to: $b = new Child(); $a = new Master( $b ); it works of course. In general destructors should never be called if the constructor was not called or even if it did not finish. Reproduce code: --------------- class Master { public function __construct( $child ) { echo __CLASS__, "::__construct() [", get_class( $this ), "]\n"; } public function __destruct() { echo __CLASS__, "::__destruct() [", get_class( $this ), "]\n"; } } class Child { public function __construct() { echo __CLASS__, "::__construct() [", get_class( $this ), "]\n"; throw new Exception( "Child failure" ); } public function __destruct() { echo __CLASS__, "::__destruct() [", get_class( $this ), "]\n"; } } $a = new Master( new Child() ); Expected result: ---------------- Child::__construct() [Child] Actual result: -------------- Child::__construct() [Child] Master::__destruct() [Master] ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=39868&edit=1

« previous php.bugs (#106495) next »