Re: Closure and $this

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Wed, Jan 12, 2011 at 10:57 PM, Larry Garfield <larry@xxxxxxxxxxxxxxxx>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

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux