是“使用”吗?关键字可用于 5.3 之前的函数闭包吗?
天哪,我什至无法在 PHP 网站上找到“使用”的文档(除了命名空间的上下文 - 顺便说一句,模糊关键字真是太好了)。
有人可以确认 function() use ($foo) { }
仅在 5.3 及更高版本中可用吗?您在哪里找到该记录?
作为额外的好处,您将如何编写无法使用“use”的代码(例如:使用 create_function($args, $funcname) 作为 array_map() 的回调)?
Hell, I can't even FIND the documentation for 'use' on the PHP site (other than in the context of namespaces - nice job ambiguating a keyword BTW).
Can someone confirm that function() use ($foo) { }
is only available in 5.3 and later? And where did you find that documented?
As an added bonus, how would you code around not being able to use 'use' (eg: with create_function($args, $funcname) as the callback for array_map())?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
闭包是在 5.3 中引入的,因此
use
与闭包结合使用也可以在 5.3 或更高版本中使用(当然)。我不完全理解这个问题,但是因为闭包和带有闭包的
use
都具有相同的版本,没有任何情况不能将use
与闭包一起使用。要么两者都有,要么什么都不做 (--> <5.3)http://php.net/functions.anonymous
发行说明 5.3.0
Closures are introduced in 5.3, thus
use
in conjunction with closures are also available in 5.3 or later (of course).I don't understand the question completely, but because both closures and
use
with closures comes with the same version, there is no situation, where you can not useuse
with closures. Either both, or nothing (--> <5.3)http://php.net/functions.anonymous
Release Notes 5.3.0
在没有闭包的情况下,在 5.3 之前的世界中,如果您想避免 create_function() 但需要将变量从外部作用域绑定到回调类型函数,请将函数包装在一个类中,并将外部变量传递给该类实例化。
如果您经常这样做,您可能会发现以下通用包装类很有用(或丑陋,或两者兼而有之,就像我一样):
我实际上会将其放入外部文件(callbacks.php)中,然后继续添加您的回调代码这个类的公共方法。显然,只有当你经常这样做时,这才会带来好处。否则,只需创建一个一次性包装类,其构造函数接受您要包含的特定数量的参数。
然后可以使用两个参数形式来利用此通用代码来指定回调:
通用包装器接受任意数量的参数并将它们作为成员(实例)变量添加到类中,然后可以按 $this->gt 的顺序访问该类;user1、$this->user2 等(初始索引为 1)。
希望这对某人有用。在某个时刻。或许。
In the absence of closures, in a pre 5.3 world, if you want to avoid create_function() but need to bind variables from an external scope to a callback type function, wrap the function in a class, to which you pass your external variables upon instantiation.
If you do this a lot, you may find the following generic wrapper class useful (or ugly, or both as do I):
I would actually put this in an external file (callbacks.php) and then just keep adding your callback code a public methods of this class. Obviously, this only pays dividends if you're going to do this frequently; otherwise, just create a one-off wrapper class whose constructor accepts the specific number of arguments you're looking to include.
This generic code can then be leveraged using the two-argument form for specifying a callback:
The generic wrapper takes any number of arguments and adds them as member (instance) variables to the class that can then be accessed in order as $this->user1, $this->user2 etc (initial index is 1).
Hope this is of some use to someone. At some point. Maybe.