Why can I not use $this as a lexical variable in PHP 5.5.4?

后端 未结 8 1615
再見小時候
再見小時候 2020-12-04 01:12
$ 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


        
相关标签:
8条回答
  • 2020-12-04 02:10

    I know, this is an old question, but maybe someone from google find this:

    The reason why you get the error is, because you can't use an already defined variable name as lexical variable in the same closure.

    Since in PHP 5.5 and above you can access $this inside the closure, a variable with the name $this already exists.

    Here is another example, where you would get the same error:

    $item = "Test 1";
    $myFnc = function($item) use ($item) {
        ...
    }
    $myFnc("Test 2");
    

    As you can see, the $item is already used as closure parameter, so you can't us it lexical variable.

    0 讨论(0)
  • 2020-12-04 02:12

    I don't know the answer to your actual question (ie Why can't you do it), but I can give you a work around: Use a temporary copy of $this and use() that instead:

    class Foo
    {
        public function bar()
        {
            $that = $this;
            return function() use($that)
            {
                print_r($that);
            };
        }
    }
    

    I've just tested it, and this does work.

    0 讨论(0)
提交回复
热议问题