Re: Closure and $this
| From: | David Harkness | Date: | Thu, 13 Jan 2011 18:52:57 +0000 |
| Subject: | Re: Closure and $this | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-310741@lists.php.net to get a copy of this message | ||
On Wed, Jan 12, 2011 at 10:57 PM, Larry Garfield <larry@garfieldtech.com>wrote:
> I believe this is the relevant RFC:
>
> http://wiki.php.net/rfc/closures/object-extension
>
That was a good bedtime read last night, Larry. I prefer method A which is
nearly identical to Java's inner classes where $this would remain tied to
whatever it held when the closure was created and gain the object's scope. I
do like the idea of being able to explicitly bind the closure to a new
object as well.
That's all well and good come PHP 5.4 or 6.0, but for now you are limited to
holding a reference to $this without gaining its scope, i.e. you can only
access public members. Also, you must assign $this to a new variable because
you cannot pass $this in the use() clause.
$that = $this;
$closure = function(...) use ($that) { ... $that->property ...
$that->method() ... }
If you need access to a protected or private variable inside the closure,
you can pass a reference to it inside use(). Once again you need to first
assign the reference to a new variable and then pass that in to the closure.
Important: you must use the & operator in the use() clause as well as when
creating the reference.
class ClosureFactory
{
private $count = 0;
public function create() {
$ref = &$this->count;
return function() use (&$ref) {
return ++$ref;
};
}
}
$factory = new ClosureFactory();
$closure = $factory->create();
for ($i = 0; $i < 5; $i++) {
echo $closure();
}
Yields
12345
David