note 123498 added to functions.anonymous
| From: | jake dot tunaley at berkeleyit dot com | Date: | Mon, 07 Jan 2019 05:04:51 +0000 |
| Subject: | note 123498 added to functions.anonymous | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-210018@lists.php.net to get a copy of this message | ||
Beware of using $this in anonymous functions assigned to a static variable.
<?php
class Foo {
public function bar() {
static $anonymous = null;
if ($anonymous === null) {
// Expression is not allowed as static initializer workaround
$anonymous = function () {
return $this;
};
}
return $anonymous();
}
}
$a = new Foo();
$b = new Foo();
var_dump($a->bar() === $a); // True
var_dump($b->bar() === $a); // Also true
?>
In a static anonymous function, $this will be the value of whatever object instance that method was
called on first.
To get the behaviour you're probably expecting, you need to pass the $this context into the
function.
<?php
class Foo {
public function bar() {
static $anonymous = null;
if ($anonymous === null) {
// Expression is not allowed as static initializer workaround
$anonymous = function (self $thisObj) {
return $thisObj;
};
}
return $anonymous($this);
}
}
$a = new Foo();
$b = new Foo();
var_dump($a->bar() === $a); // True
var_dump($b->bar() === $a); // False
?>
----
Server IP: 208.43.231.9
Probable Submitter: 2a02:cb43:e::301 (proxied: 1.152.110.153)
----
Manual Page -- http://php.net/manual/en/functions.anonymous.php
Edit -- https://master.php.net/note/edit/123498
Del: integrated -- https://master.php.net/note/delete/123498/integrated
Del: useless -- https://master.php.net/note/delete/123498/useless
Del: bad code -- https://master.php.net/note/delete/123498/bad+code
Del: spam -- https://master.php.net/note/delete/123498/spam
Del: non-english -- https://master.php.net/note/delete/123498/non-english
Del: in docs -- https://master.php.net/note/delete/123498/in+docs
Del: other reasons-- https://master.php.net/note/delete/123498
Reject -- https://master.php.net/note/reject/123498
Search -- https://master.php.net/manage/user-notes.php