note 114546 added to functions.anonymous
| From: | andris at codeaid dot net | Date: | Wed, 05 Mar 2014 12:34:01 +0000 |
| Subject: | note 114546 added to functions.anonymous | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-198797@lists.php.net to get a copy of this message | ||
Haven't seen it documented anywhere but PHP 5.4 now allows accessing private and protected
members of an object if it's passed into a lambda function:
<?php
class Scope
{
protected $property = 'default';
// or even
// private $property = 'default';
public function run()
{
$self = $this;
$func = function() use ($self) {
$self->property = 'changed';
};
$func();
var_dump($this->property);
}
}
$scope = new Scope();
$scope->run();
?>
When running the file under PHP 5.3 you get the following error message:
* Fatal error: Cannot access protected property Scope::$property in ./file.php on line 11
PHP 5.4, however, does not complain and outputs "changed" as expected.
Not sure why it's like that but I suspect it has something to do with 5.4 supporting passing
$this into lambda functions.
Speaking of which, something to remember is that the following won't work:
<?php
$func = function() use ($this) {
$this->property = 'changed';
};
?>
The error you'll get is:
* PHP Fatal error: Cannot use $this as lexical variable in ./file.php on line 9
You have to totally omit the use statement for it to work:
<?php
$func = function() {
$this->property = 'changed';
};
?>
----
Server IP: 72.52.91.14
Probable Submitter: 72.52.91.14
----
Manual Page -- http://php.net/manual/en/functions.anonymous.php
Edit -- https://master.php.net/note/edit/114546
Del: integrated -- https://master.php.net/note/delete/114546/integrated
Del: useless -- https://master.php.net/note/delete/114546/useless
Del: bad code -- https://master.php.net/note/delete/114546/bad+code
Del: spam -- https://master.php.net/note/delete/114546/spam
Del: non-english -- https://master.php.net/note/delete/114546/non-english
Del: in docs -- https://master.php.net/note/delete/114546/in+docs
Del: other reasons-- https://master.php.net/note/delete/114546
Reject -- https://master.php.net/note/reject/114546
Search -- https://master.php.net/manage/user-notes.php