Bug #75228 [Opn->Nab]: anonymous function keep context if does not need
| From: | requinix@php.net | Date: | Tue, 19 Sep 2017 14:26:44 +0000 |
| Subject: | Bug #75228 [Opn->Nab]: anonymous function keep context if does not need | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-211245@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=75228&edit=1
ID: 75228
Updated by: requinix@php.net
Reported by: milan dot matejcek at gmail dot com
Summary: anonymous function keep context if does not need
-Status: Open
+Status: Not a bug
Type: Bug
Package: Class/Object related
Operating System: linux
PHP Version: 5.6.31
Block user comment: N
Private report: N
New Comment:
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
> As of PHP 5.4.0, when declared in the context of a class, the current class is
> automatically bound to it, making $this available inside of the function's
> scope. If this automatic binding of the current class is not wanted, then static
> anonymous functions may be used instead.
http://php.net/manual/en/functions.anonymous.php
Previous Comments:
------------------------------------------------------------------------
[2017-09-19 14:16:01] milan dot matejcek at gmail dot com
Description:
------------
I tried on version php5.6-7.2 here is same behavior like in test script.
I create anonymous function in class body, in function i don't need context $this but anonymous
function keep the reference to Foo object in memory until end of run time. Foo class has not defined
variable by myself.
In test script is hack like class bar.
Test script:
---------------
class MyClass
{
public $event;
}
class Foo
{
public function __construct(MyClass $bar)
{
$bar->event = function () {
// this keep reference on $this, when i don't use $this
};
}
public function __destruct()
{
echo __CLASS__ . ' ';
}
}
// hack how remove reference for context
class Bar
{
public function __construct(MyClass $bar)
{
$bar->event = self::createAnonymousFunction();
}
private static function createAnonymousFunction()
{
return function () {
// this does not keep reference
};
}
public function __destruct()
{
echo __CLASS__ . ' ';
}
}
$myClass1 = new MyClass();
$myClass2 = new MyClass();
new Foo($myClass1);
new Bar($myClass2);
echo "Hello ";
Expected result:
----------------
Foo Bar Hello
Actual result:
--------------
Bar Hello Foo
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=75228&edit=1