|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #75228 anonymous function keep context if does not need
Submitted: 2017-09-19 14:16 UTC Modified: 2017-09-19 14:44 UTC
From: milan dot matejcek at gmail dot com Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: 5.6.31 OS: linux
Private report: No CVE-ID: None
 [2017-09-19 14:16 UTC] milan dot matejcek at gmail dot com
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


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2017-09-19 14:26 UTC]
-Status: Open +Status: Not a bug
 [2017-09-19 14:26 UTC]
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at and the instructions on how to report
a bug at

> 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.
 [2017-09-19 14:39 UTC] milan dot matejcek at gmail dot com
I understand, current class is automatically bound. Is it possible add condition for bounding? Is it context need in anonymous function? Because object is in memory, but i have'nt defined variable for this object.
 [2017-09-19 14:44 UTC]
> Is it possible add condition for bounding?
Not really. But it is possible to make static closures very easily, as the documentation demonstrates.
 [2017-09-19 14:50 UTC] milan dot matejcek at gmail dot com
I'm soory. You have right.
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Tue May 21 11:01:34 2024 UTC