$ 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
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.
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.