How to remove a function at runtime in PHP?


The functions and classes in PHP have global scope. This means they could be called outside a function even after they were defined inside the scope and the other way round.

But PHP doesn't support function overloading, and it is not possible to redefine previously-declared functions.

The function can be defined as an anonymous function and it can be unset after it completes its run.

Below is a code sample for the same −

if (function_exists('get_magic_quotes_gpc') && @get_magic_quotes_gpc())
   $my_fn = create_function('&$v, $k', '$v = stripslashes($v);');
   array_walk_recursive(array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST), $my_fn);
   unset($my_fn);
}

An anonymous function can't be called inside itself. The workaround is to use array_walk_recursive.

Updated on: 06-Apr-2020

455 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements