I know this question seems hacky and weird, but is there a way to remove a function at runtime in PHP?
I have a recursive function declared in a \"if\" block and wan
I agree with Alix. You can, however, avoid the function being called from anywhere else by getting rid of the function. Rewrite the recursive function as an iterative loop. You'll have the added benefit of reduce memory usage.
UPDATE: with your code example, I'm not sure why you feel the need to prevent this function from being called again. It simply formats some strings in an array recursively... again, you could do this iteratively and avoid having a function in the first place. Otherwise, just leave it there and don't call it again.
From the PHP Manual on Functions:
All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa. [...] PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.
The exception is through runkit. However, you could define your function as an anonymous function and unset it after you ran it, e.g.
if (function_exists('get_magic_quotes_gpc') && @get_magic_quotes_gpc())
$fn = create_function('&$v, $k', '$v = stripslashes($v);');
array_walk_recursive(array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST), $fn);
unset($fn);
}
Some commentors correctly pointed out (but not an issue any longer in PHP nowadays), you cannot call an anonymous function inside itself. By using array_walk_recursive
you can get around this limitation. Personally, I would just create a regular function and not bother about deleting it. It won't hurt anyone. Just give it a proper name, like stripslashes_gpc_callback
.
Note: edited and condensed after comments
As of PHP 5.3 you can use an anonymous function:
$anonymous_function = function($value){
// do stuff
};
Call it like this:
$returned_value = $anonymous_function('some parameter');
To delete the function, just unset the variable:
unset($anonymous_function);
Here is an example of how to implement your function:
$stripslashes_deep = function (&$object){
global $stripslashes_deep;
if(is_array($object))
foreach($object as &$value){
if(is_array($value))
$stripslashes_deep($value);
else
$value = stripslashes($value);
}
};
anonymous functions has no name. So you can't use array_map, as it will only take a function name as parameter.
anonymous functions has the variable scope. So you have to declare the variable containing the function as global, to reach it from within a recursive function.
Unfortunately if you define a regular function inside the anonymous function, it will be globally available, even after you unset the variable. (I don't really see the benefit of that. I hope it's a blunder to be corrected later :-)