就像我们取消设置变量一样,如何取消设置函数定义?

问题描述:

我想定义一个函数并在使用后取消设置它,就像处理变量一样.

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

就像这样,如果我声明一个函数 callMethod(),是否可以取消设置它?

Just like this if i declare a function callMethod(), is there a way to unset it?

从PHP 5.3开始,您可以分配将匿名函数设置为变量,然后将其取消设置:

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

在5.3之前,您可以使用 create_function() 做类似的事情

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