Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

$ 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 

The following code (similar to example at https://bugs.php.net/bug.php?id=49543):

class Foo {     public function bar()     {         return function() use ($this)         {             echo "in closure\n";         };     } } 

fails with:

PHP Fatal error:  Cannot use $this as lexical variable 

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?

like image 503
tjbp Avatar asked Oct 17 '13 15:10

tjbp


People also ask

Can we use $this as variable in PHP?

In PHP, this is declared like a variable declaration (with the '$' sign) even though it is a reserved keyword. More specifically, $this is a special read-only variable that is not declared anywhere in the code and which represents a value that changes depending on the context of program execution.

What does & in front of variable mean PHP?

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable).


2 Answers

So it seems $this can be used simply if it isn't specified via the "use" keyword.

The following echoes 'bar':

class Foo {     private $foo = 'bar';      public function bar()     {         return function()         {             echo $this->foo;         };     } }  $bar = (new Foo)->bar();  $bar(); 

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

like image 67
tjbp Avatar answered Oct 10 '22 12:10

tjbp


In PHP 5.3 if you are using a Closure inside of a class, the Closure will not have access to $this.

In PHP 5.4, support has been added for the usage of $this in Closures.

like image 27
coolstoner Avatar answered Oct 10 '22 12:10

coolstoner