note 97297 deleted from functions.anonymous by danbrown
| From: | danbrown@php.net | Date: | Tue, 13 Apr 2010 02:41:43 +0000 |
| Subject: | note 97297 deleted from functions.anonymous by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-168185@lists.php.net to get a copy of this message | ||
Note Submitter: Hayley Watson
----
Pending a decision on what it should mean, $this is not currently (as of 5.3.2) usable within
anonymous functions.
There are roughly two positions (plus attempts at compromise), that can be called "early"
and "late".
Early: $this refers to the object in whose scope the anonymous function is constructed.
<?php
class Creator
{
public function make_anonymous()
{
return function()
{
return $this;
};
}
}
class Caller
{
public $p;
public function call_anonymous($f)
{
$this->p = $f();
}
}
$alpha = new Creator;
$omega = new Caller;
$omega->call_anonymous($alpha->create_anonymous());
// $omega->p === $alpha
?>
Late: $this refers to the object in whose scope the anonymous function is called.
<?php
class Creator
{
public function make_anonymous()
{
return function()
{
return $this;
};
}
}
class Caller
{
public $p;
public function call_anonymous($f)
{
$this->p = $f();
}
}
$alpha = new Creator;
$omega = new Caller;
$omega->call_anonymous($alpha->create_anonymous());
// $omega->p === $omega
?>
So until this is cleared up, $this won't work in an anonymous function. (Personally, I favour
the early method; otherwise the anonymous function - and therefore its Creator - has access to all
of the Caller's private properties.)