Skip to content

Instantly share code, notes, and snippets.

@sanmai
Last active August 29, 2015 14:04
Show Gist options
  • Save sanmai/f271b89cf306634ba123 to your computer and use it in GitHub Desktop.
Save sanmai/f271b89cf306634ba123 to your computer and use it in GitHub Desktop.
Cancellable register_shutdown_function
<?php
/**
* @author Alexey Kopytko
* @license MIT license
*/
include 'register_cancellable_shutdown_function.php';
$first = register_cancellable_shutdown_function(function () {
echo "This function is never called\n";
});
$second = register_cancellable_shutdown_function(function () {
echo "This function is going to be called\n";
});
cancel_shutdown_function($first);
<?php
/**
* @author Alexey Kopytko
* @license MIT license
*/
function register_cancellable_shutdown_function($callback)
{
return new cancellable_shutdown_function_envelope($callback);
}
function cancel_shutdown_function(cancellable_shutdown_function_envelope $envelope)
{
$envelope->cancel();
}
final class cancellable_shutdown_function_envelope
{
private $callback;
public function __construct($callback)
{
$this->callback = $callback;
register_shutdown_function(function () {
$this->callback && call_user_func($this->callback);
});
}
public function cancel()
{
$this->callback = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment