Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = "lambda_1";
echo $func2('test2.a'), "
"; // Same results, this is the "unset" $func function

echo $func('test2.b'); // Fatal Error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...