为什么我不能在 PHP 5.5.4 中使用 $this 作为词法变量?

php
2022-08-30 11:38:30
$ 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对该错误报告的评论,在匿名函数中使用$this是从PHP 5.4开始添加的。我做错了什么?


答案 1

因此,似乎没有通过“use”关键字指定,则似乎可以简单地使用$this。

以下回显“bar”:

class Foo
{
    private $foo = 'bar';

    public function bar()
    {
        return function()
        {
            echo $this->foo;
        };
    }
}

$bar = (new Foo)->bar();

$bar();

这在php-internals邮件列表中被报告,并且显然是由于5.3缺乏对此功能的支持而悬而未决的:

http://marc.info/?l=php-internals&m=132592886711725


答案 2

如果在类中使用闭包,则 将无权访问 。PHP 5.3Closure$this

在 中,添加了对 在 的使用的支持。PHP 5.4$thisClosures


推荐