note 94894 deleted from language.oop5.decon by danbrown
| From: | danbrown@php.net | Date: | Tue, 01 Dec 2009 16:02:30 +0000 |
| Subject: | note 94894 deleted from language.oop5.decon by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-163450@lists.php.net to get a copy of this message | ||
Note Submitter: Sascha Ziemann
----
Destructors are called in a stupid first-in-last-out stack order and do not honor any referential
dependencies. The following example works fine as long as you instantiate ClassB after ClassA:
class ClassA
{
function hello () { echo "A hello\n"; }
function __construct () { echo "A __construct\n"; }
function __destruct () { echo "A __destruct\n"; }
}
class ClassB
{
function __construct () { echo "B __construct\n"; }
function __destruct ()
{
echo "B __destruct\n";
global $a;
$a->hello();
}
}
$a = new ClassA;
$b = new ClassB;
As you can see the destructors get called in reverse order of the constructors:
$ php ./test.php
A __construct
B __construct
B __destruct
A hello
A __destruct
If you switch the order by creating $b before $a you will get a fatal error:
$ php ./test.php
B __construct
A __construct
A __destruct
B __destruct
Fatal error: Call to a member function hello() on a non-object in test.php on line 18
This makes the use of destructors quite useless for tasks, which require proper dependency handling
like freeing database statements before the database connection gets closed. Destructors can only be
used for completely static and independent jobs.