I want to define a function and unset it after its use just like we do with variables.
$a = 'something'; unset($a); echo $a; // outputs nothing
Just like this if i declare a function callMethod(), is there a way to unset it?
The unset() function is a predefined variable handling function of PHP, which is used to unset a specified variable. In other words, "the unset() function destroys the variables".
Definition and Usage The function unset() destroys the specified variables. The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy. If a globalized variable is unset() inside of a function, only the local variable is destroyed.
Form the unset entry in the bash manpage: If -f is specified, each name refers to a shell function, and the function definition is removed. Note: -f is only really necessary if a variable with the same name exists. If you do not also have a variable named foo , then unset foo will delete the function.
The unset() function in PHP resets any variable. If unset() is called inside a user-defined function, it unsets the local variables. If a user wants to unset the global variable inside the function, then he/she has to use $GLOBALS array to do so.
As of PHP 5.3, you can assign an anonymous function to a variable, then unset it:
$upper = function($str) { return strtoupper($str); }; echo $upper('test1'); // outputs: TEST1 unset($upper); echo $upper('test2'); // Notice: Undefined variable: upper // Fatal error: Function name must be a string
Before 5.3, you can do something similar with create_function()
$func = create_function('$arg', 'return strtoupper($arg);'); echo $func('test1'); unset($func); $func2 = "\0lambda_1"; echo $func2('test2.a'), "\n"; // Same results, this is the "unset" $func function echo $func('test2.b'); // Fatal Error
runkit_function_remove — Remove a function definition http://php.net/manual/en/function.runkit-function-remove.php
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