在单个语句中创建和调用匿名函数
php 闭包或匿名函数用于创建函数而不指定其名称。
是否可以像 JavaScript 中那样在不分配标识符的情况下调用它们? 例如,
(function(){
echo('anonymous function');
})();
在定义匿名函数时,use
构造的正确用法是什么,以及在可访问私有属性的公共方法中匿名函数的状态是什么?
$anon_func =
function($my_param) use($this->object_property){ //use of $this is erroneous here
echo('anonymous function');
};
A php closure or anonymous function is used to create function without specifying its name.
Is it possible to call them without assigning to identifier as we do in JavaScript ?
e.g.
(function(){
echo('anonymous function');
})();
What is the correct use of use
construct while defining anonymous function and what is the status of anonymous function in public method with accessibility to private properties?
$anon_func =
function($my_param) use($this->object_property){ //use of $this is erroneous here
echo('anonymous function');
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
PHP 7 添加了执行此操作的功能。
这段代码:
在 PHP 7 中可以正常工作。(它仍然无法在任何 PHP 5.x. 版本中工作)
PHP 7 added the ability to do this.
This code:
works as one would expect in PHP 7. (It still doesn't work in any PHP 5.x. release)
PHP 5.x 中没有;除非您在方法将回调作为参数时进行计数。例如:
use
关键字指示应将当前词法范围中的哪些变量导入到闭包中。您甚至可以通过引用传递它们并更改传递的变量,例如:类内部定义的闭包可以完全访问其所有属性和方法,包括私有属性和方法,无需通过 PHP 5.4:
请注意,由于某些奇怪的原因,支持
$this 在 PHP 5.3 中被删除。在此版本中,您可以使用以下方法解决此限制:
但这仅允许您访问公共成员,尝试访问私有成员仍会出现错误。
另请注意,尝试导入
$this
(通过use
),无论 PHP 版本如何,都将导致致命错误Cannot use $this as lexical variable< /代码>。
Not in PHP 5.x; unless you count it when your method takes a callback as an argument. eg:
The
use
keyword indicates which variables from the current lexical scope should be imported into the closure. You can even pass them by reference and change the variable being passed, eg:Closures defined inside a class have full access to all its properties and methods, including private ones with no need to import
$this
through the keyworduse
in PHP 5.4:Note that for some strange reason support for
$this
in closures was removed in PHP 5.3. In this version, you can work around this restriction using something like:But this gives you access to public members only, attempting to access private members will still give you an error.
Also note that attempting to import
$this
(viause
), regardless of the PHP version, will result in a fatal errorCannot use $this as lexical variable
.看起来不像,因为它们仍然必须使用
function() {}
表示法进行声明,并且在我的 5.3.2 安装中,尝试您的示例概念会返回一个意外的 '( '
语法错误。关于闭包的 doc 页面 没有 。也许一旦他们修补解析器以允许
somefunction()[2]
数组取消引用,这就会成为可能Doesn't look like it, as they still have to be declared with the
function() {}
notation, and on my 5.3.2 install, trying your sample notion returns anunexpected '('
syntax error. The doc page on closures doesn't mention it either.Maybe it'll become possible once they patch up the parser to allow
somefunction()[2]
array dereferencing.示例 1
示例 2
示例 3
example 1
example 2
example 3