- var_dump: documentation ( source)
<?php
// If this would be for real, decorators would directly replace
// the decorated functions/methods.
function decorate(callable $fn, array $decorators)
{
foreach ($decorators as $d) {
$wrapper = $d($fn);
$fn = $wrapper;
}
return $wrapper;
}
function foo($bar)
{
throw new Exception("Error $bar!");
}
function catch_all_exceptions(callable $fn)
{
return function() use ($fn) {
try {
return call_user_func_array($fn, func_get_args());
} catch (\Exception $e) {
echo "catch_all_exceptions: Caught Exception: $e\n";
}
};
}
function once(callable $fn) {
return function() use ($fn) {
static $return;
static $called = false;
if (!$called) {
$return = call_user_func_array($fn, func_get_args());
$called = true;
}
return $return;
};
}
function do_something_before(callable $fn)
{
return function() use ($fn) {
echo "Before!\n";
return call_user_func_array($fn, func_get_args());
};
}
$bar = decorate(function() { echo "Hello\n"; }, ["once"]);
$bar();
$bar();
$bar();
$foo = decorate("foo", ["catch_all_exceptions", "do_something_before"]);
var_dump($foo("bar"));