Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...