<?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"));
- Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.20, 7.2.0 - 7.2.33, 7.3.12 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
- Hello
Before!
catch_all_exceptions: Caught Exception: Exception: Error bar! in /in/PQhSI:17
Stack trace:
#0 /in/PQhSI(24): foo('bar')
#1 /in/PQhSI(49): {closure}('bar')
#2 /in/PQhSI(59): {closure}('bar')
#3 {main}
NULL
- Output for 5.4.0 - 5.4.45, 5.5.24 - 5.5.35, 5.6.7 - 5.6.28
- Hello
Before!
catch_all_exceptions: Caught Exception: exception 'Exception' with message 'Error bar!' in /in/PQhSI:17
Stack trace:
#0 [internal function]: foo('bar')
#1 /in/PQhSI(24): call_user_func_array('foo', Array)
#2 [internal function]: {closure}('bar')
#3 /in/PQhSI(49): call_user_func_array(Object(Closure), Array)
#4 /in/PQhSI(59): {closure}('bar')
#5 {main}
NULL
- Output for 5.3.0 - 5.3.29
- Parse error: syntax error, unexpected '[' in /in/PQhSI on line 53
Process exited with code 255. - Output for 5.1.0 - 5.1.6, 5.2.0 - 5.2.17
- Parse error: syntax error, unexpected T_FUNCTION in /in/PQhSI on line 22
Process exited with code 255. - Output for 5.0.0 - 5.0.5
- Parse error: parse error, unexpected T_ARRAY, expecting '&' or T_VARIABLE in /in/PQhSI on line 5
Process exited with code 255. - Output for 4.4.2 - 4.4.9
- Parse error: syntax error, unexpected T_STRING, expecting ')' in /in/PQhSI on line 5
Process exited with code 255. - Output for 4.3.0 - 4.3.1, 4.3.5 - 4.3.11, 4.4.0 - 4.4.1
- Parse error: parse error, unexpected T_STRING, expecting ')' in /in/PQhSI on line 5
Process exited with code 255. - Output for 4.3.2 - 4.3.4
- Parse error: parse error, expecting `')'' in /in/PQhSI on line 5
Process exited with code 255.
preferences:
224.06 ms | 401 KiB | 316 Q