note 123497 added to language.variables.scope

From: Date: Mon, 07 Jan 2019 05:02:27 +0000
Subject: note 123497 added to language.variables.scope
Groups: php.notes 
Request: Send a blank email to php-notes+get-210017@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/language.variables.scope.php Edit -- https://master.php.net/note/edit/123497 Del: integrated -- https://master.php.net/note/delete/123497/integrated Del: useless -- https://master.php.net/note/delete/123497/useless Del: bad code -- https://master.php.net/note/delete/123497/bad+code Del: spam -- https://master.php.net/note/delete/123497/spam Del: non-english -- https://master.php.net/note/delete/123497/non-english Del: in docs -- https://master.php.net/note/delete/123497/in+docs Del: other reasons-- https://master.php.net/note/delete/123497 Reject -- https://master.php.net/note/reject/123497 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#210017) next »