php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #45604 Lambda functions and $this scope
Submitted: 2008-07-23 12:07 UTC Modified: 2008-07-23 23:05 UTC
Votes:1
Avg. Score:3.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:0 (0.0%)
Same OS:0 (0.0%)
From: george at noodles dot gr Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.3CVS-2008-07-23 (snap) OS: *
Private report: No CVE-ID: None
 [2008-07-23 12:07 UTC] george at noodles dot gr
Description:
------------
When creating a normal function inside a class and calling it, the function doesn't have access to $this.
"Fatal error: Using $this when not in object context"

When creating a lambda function inside a class, $this is visible from the new function's scope and can be accessed normally.

Wouldn't it be better (and maybe safer) to allow the use of $this as a closure instead of passing it to the new lambda function?
Currently trying to use $this as a closure dies with a "Fatal error: Cannot use $this as lexical variable" error.

Example for the suggestion.
$x = function () use ($this) { return $this->hello; };

Reproduce code:
---------------
<?php

class something
{
	public $hello = 'Hello world!';
	
	public function world()
	{
		$x = function () { return $this->hello; };		
		return $x();
	}
}

$s = new something();
echo $s->world();

?>

Expected result:
----------------
Not to be able to use $this.


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-07-23 13:48 UTC] jani@php.net
Please report this kind of things to internals@lists.php.net as this feature is still under heavy development and jury is out to decide such things.
 [2008-07-23 23:05 UTC] stas@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

This is the intended behavior. Use "static function" if you don't need $this.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed May 07 05:01:27 2025 UTC