Last active
August 29, 2015 14:04
-
-
Save sanmai/f271b89cf306634ba123 to your computer and use it in GitHub Desktop.
Cancellable register_shutdown_function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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