Redefine and then restore a function with Runkit

Sometimes during PHP unit testing You'll need to redefine a function, and then - later - restore it to it's original state. One way to do that with Runkit ... Let's say that we don't want to get "Cannot modify header information - headers already sent by" error messages when testing a code which uses setcookie php command. We can use the following trick:

use it with caution, and do not forget to RESTORE the function - or it may surprise you !

// mock setcookie
 
// mock setcookie
runkit_function_copy('setcookie','setcookie_ORIGINAL');
runkit_function_redefine('setcookie','','return true;');
 
 
// functional code here
 
 
// restore setcookie, cleanup
runkit_function_remove('setcookie');
runkit_function_copy('setcookie_ORIGINAL','setcookie');
runkit_function_remove('setcookie_ORIGINAL');