Created
December 6, 2010 12:21
-
-
Save CHH/730212 to your computer and use it in GitHub Desktop.
Wrap a function inside another function
This file contains 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 | |
function func_wrap($fn, $wrapper) | |
{ | |
// Unify calling of the wrapped function | |
if(is_array($fn) or is_string($fn)) { | |
$original = function() use ($fn) { | |
return call_user_func_array($fn, func_get_args()); | |
}; | |
} else { | |
$original = $fn; | |
} | |
$wrapped = function() use ($original, $wrapper) { | |
$args = func_get_args(); | |
array_unshift($args, $original); | |
return call_user_func_array($wrapper, $args); | |
}; | |
return $wrapped; | |
} | |
$a = function() { | |
return 1; | |
}; | |
$b = func_wrap($a, function($original) { | |
return $original() + 2; | |
}); | |
echo $b(); // -> 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment