Summary:
* use destructors to perform a cleanup in case of exception.
PHP calls method __destruct() on instance of class when variable storing the instance goes out-of-scope (or gets unset). This works for function leave by Exception, aside of plain return. (same as for C++, AFAIK)
aFunction() {
$i = new LockerClass();
throw new MinorErrorEx('Warn user & perform some other activity');
// $i->__destruct() gets called before stack unwind begins, unlocking whatever get locked by new LockerClass();
return $bar;
}
(A lengthy) example:
Let's say you need to perform a series of operaions on SQL database that should not get disrupted. You lock the tables:
<?php
function updateStuff() {
DB::query('LOCK TABLES `a`, `b`, `c` WRITE');
someFunction();
DB::query('UNLOCK TABLES');
} ?>
Now, let's supouse that someFunction() may throw an exception. This would leave us with the tables locked, as the second DB::query() will not get called. This pretty much will cause the next query to fail. You can do it like:
<?php
function updateStuff() {
DB::query('LOCK TABLES `a`, `b` WRITE');
try {
someFunction(); }
catch ( Exception $e ) {
DB::query('UNLOCK TABLES');
throw $e;
}
DB::query('UNLOCK TABLES')
} ?>
However, this is rather ugly as we get code duplication. And what if somebody later modifies updateStuff() function in a way it needs another step of cleanup, but forget to add it to catch () {}? Or when we have multiple things to be cleaned up, of which not all will be valid all the time?
My solution using destructor: i create an instance of class DB holding a query unlocking tables which will be executed on destruction.
<?php
function updateStuff() {
$SQLLocker = DB::locker( array('a', 'b'), array('b') );
someFunction();
DB::query('UNLOCK TABLES');
}
class DB {
function locker ( $read, $write ) {
DB::query( );
$ret = new DB;
$ret->onDestruct = 'UNLOCK TABLES';
return $ret;
}
function _destructor() {
if ( $this->onDestruct )
DB::query($this->onDestruct);
}
}
?>