在函数内创建函数有什么用?
我知道可以在另一个函数中创建一个函数。为什么人们在现实生活中需要这样做? (PHP)
function someFunction($var)
{
function anotherFunction()
{
return M_PI;
}
return anotherFunction();
}
I know that it is possible to create a function within another function. Why might one need to do that in real life? (PHP)
function someFunction($var)
{
function anotherFunction()
{
return M_PI;
}
return anotherFunction();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您唯一真正想要在另一个函数内部定义一个函数的情况是,在调用外部函数之前,您不希望该内部函数对任何东西可用。
您唯一需要(或希望)
unload_my_library
可用的时间是在加载库之后。The only time you'd ever really want to define a function inside of another function is if you didn't want that inner function available to anything until the outer function is called.
The only time you'd need (or want)
unload_my_library
to be available is after the library has been loaded.通常不应使用嵌套函数。类和公共/私有方法可以更干净地解决相同类型的问题。
然而,函数生成函数可能很有用:
这个例子是做作的而且愚蠢的,但是这种事情对于生成排序例程等使用的函数很有用。
Nested functions generally shouldn't ever be used. Classes and public/private methods solve the same sorts of problems much more cleanly.
However, function generating functions can be useful:
This example is contrived and silly, but this sort of thing can be useful for generating functions used by sorting routines, etc.
我在这里猜测,但我相信它用于将函数传递给另一个函数来执行。例如,调用搜索函数,您可以在其中指定回调函数来执行搜索顺序比较。这将允许您将比较器封装在外部函数中。
I'm guessing here, but I believe that it is used for passing the function to another function for execution. For example, calling a search function where you can specify a callback function to perform the search order comparison. This will allow you to encapsulate the comparator in your outer function.