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

Vin*_*Vin 23 php

我想定义一个函数,并在使用它之后取消它,就像我们对变量一样.

$a = 'something';
unset($a);
echo $a; // outputs nothing
Run Code Online (Sandbox Code Playgroud)

就像这样,如果我声明一个函数callMethod(),有没有办法取消它?

Wes*_*rch 23

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

$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
Run Code Online (Sandbox Code Playgroud)

在5.3之前,你可以做类似的事情 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
Run Code Online (Sandbox Code Playgroud)


rea*_*777 13

runkit_function_remove - 删除函数定义 http://php.net/manual/en/function.runkit-function-remove.php

  • 这需要PECL所以不是PHP的包.虽然功能很好. (4认同)
  • 这里唯一的答案。为什么其他人得到了支持? (2认同)