Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unset a function definition just like we unset a variable?

Tags:

php

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?

like image 984
Vinay Jeurkar Avatar asked Jan 01 '12 04:01

Vinay Jeurkar


People also ask

Which function is used to unset a variable?

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".

What does the unset () function mean?

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.

How do you unset a function in bash?

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.

What does the unset () function mean in PHP?

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.


2 Answers

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 
like image 101
Wesley Murch Avatar answered Sep 30 '22 18:09

Wesley Murch


runkit_function_removeRemove a function definition http://php.net/manual/en/function.runkit-function-remove.php

like image 25
realmag777 Avatar answered Sep 30 '22 17:09

realmag777