A function/method call results in a promise for future computation
Motivation
We want to be able to postpone the effects of a computation, for example delay printing from a function to webserver output until whole web-page is assembled
Implementation
Instead of evaluating a function, we deliver a promise - a callable with no arguments, which when forced is executed
Examples
//for simplicity handle only functions with one argument
class promise {
private $args = null;
private $func = null;
function __construct($func, $args) {
$this->func = $func;
$this->args = $args;
}
function evaluate() {
call_user_func($this->func,$this->args);
}
}
function delay( $func, $arg ) {
return array(new promise($func, $arg), 'evaluate');
}
//example use
...
$chunks[] = delay('a_printer',$a_variable);
...
foreach($chunks as $chunk ) {
if(is_callable($chunk)) {
$chunk(); //force - this does it's own printing in this example
} else {
print $chunk;
}
}