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 want that function to be "valid" only in that "if" block. I don't want this function to be callled outside this block.
I found out runkit_function_remove but runkit isn't enabled on my Web host. Is there another way to do that?
BTW I only support PHP 5.1.0.
Edit: I knew my question was hacky but here is the exact thing I want to do:
if (function_exists('get_magic_quotes_gpc') && @get_magic_quotes_gpc()) { function stripslashes_deep($value) { return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); } $_POST = array_map('stripslashes_deep', $_POST); $_GET = array_map('stripslashes_deep', $_GET); $_COOKIE = array_map('stripslashes_deep', $_COOKIE); $_REQUEST = array_map('stripslashes_deep', $_REQUEST); //runkit_function_remove('stripslashes_deep'); }
Since "stripslashes_deep" will only live when Magic Quotes are ON, I wanted to get rid of it when I'm done with it. I don't want people to rely on a function that isn't always there. I hope it's clearer now. Non-hacky solution suggestions are welcome too!
From the PHP Manual on user-defined 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With