为什么不能在PHP 5.5.4中将$ this用作词法变量? [英] Why can I not use $this as a lexical variable in PHP 5.5.4?
本文介绍了为什么不能在PHP 5.5.4中将$ this用作词法变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ php --version
PHP 5.5.4 (cli) (built: Sep 19 2013 17:10:06)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies
以下代码(类似于 https://bugs.php.net/bug.php?id上的示例= 49543 ):
class Foo
{
public function bar()
{
return function() use ($this)
{
echo "in closure\n";
};
}
}
失败:
PHP Fatal error: Cannot use $this as lexical variable
然而,根据PHP文档和Rasmus Lerdorf对该错误报告的评论,从PHP 5.4开始添加了$ this在匿名函数中.我在做什么错了?
Yet according to the PHP docs and a comment on that bug report from Rasmus Lerdorf, using $this in anonymous functions was added as of PHP 5.4. What am I doing wrong?
推荐答案
因此,如果未通过"use"关键字指定$ this,则似乎可以使用$ this.
So it seems $this can be used simply if it isn't specified via the "use" keyword.
以下回显"bar":
class Foo
{
private $foo = 'bar';
public function bar()
{
return function()
{
echo $this->foo;
};
}
}
$bar = (new Foo)->bar();
$bar();
这是在php-internals邮件列表中报告的,显然是由于5.3缺少对此功能的支持而造成的:
This was reported in the php-internals mailing list and is apparently overhang from 5.3's lack of support for this functionality:
http://marc.info/?l=php-internals&m=132592886711725
这篇关于为什么不能在PHP 5.5.4中将$ this用作词法变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文