note 13179 deleted from function.register-shutdown-function by jimw
| From: | jimw@php.net | Date: | Tue, 18 Dec 2001 19:46:06 +0000 |
| Subject: | note 13179 deleted from function.register-shutdown-function by jimw | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-23174@lists.php.net to get a copy of this message | ||
editor: please remove my last note. i must have done something wrong. it even crashes apache
sometimes.
here's a solution to work with objects - and even pass params to the methods.
please send your comments/improvements.
/**
* register object methods as shutdown functions.
*
* unfortunately php's register_shutdown_function() cannot work with objects and
* cannot take function parameters. this function can.
*
* the function will be called with no arguments from php's register_shutdown_function(),
* that's why we need default values (NULL) for all the params and cannot make $object
* take the param by reference as default.
*
* example:
* //register our own shutdown function
* register_shutdown_function("bs_shutdownFunction");
* //now register a method to be executed on shutdown
* bs_shutdownFunction(&$object, 'method', array('someParam',
'anotherParam'));
*
* @access public
* @param object $object (pass it by reference)
* @param string $method the method name without parenthesis (eg 'someFunction')
* @param array $params (vector) the params you want to pass along with the function. they are
passed by value.
*/
function bs_shutdownFunction($object=NULL, $method=NULL, $params=NULL) {
static $array = array();
if (!is_null($object)) {
//we have to add a method.
if (is_null($params)) {
$array[] = array(&$object, $method);
} else {
$array[] = array(&$object, $method, $params);
}
} else {
//we have to execute the registered methods.
if (isSet($array)) {
while (list($k) = each($array)) {
$object = &$array[$k][0];
$method = &$array[$k][1];
if (isSet($array[$k][2])) {
$params = &$array[$k][2];
$t = array();
while (list($key) = each($params)) {
$t[] = "\$params[$key]";
}
$evalStr = "\$object->{$method}(" . join(', ', $t) .
");";
eval($evalStr);
} else {
$object->$method();
}
}
}
}
}
//register our own shutdown function
register_shutdown_function("bs_shutdownFunction");
//create a dummy class
class somefuck {
function abc($a, $b, $c) {
copy('c:/tmp/a.gif', "c:/tmp/{$a}{$b}{$c}.gif");
}
}
//and instanciate it
$somefuck =& new somefuck();
//now register a method to be executed on shutdown
bs_shutdownFunction(&$somefuck, 'abc', array('a', 'b',
'c'));
//this will copy 'c:/tmp/a.gif' to 'c:/tmp/abc.gif'