PHP 5.4 – ‘closure $this support’

This was already planned for PHP 5.3, but

For PHP 5.3 $this support for Closures was removed because no consensus could be reached how to implement it in a sane fashion. This RFC describes the possible roads that can be taken to implement it in the next PHP version.

It indeed means you can refer to the object instance (live demo)

<?php
class A {
  private $value = 1;
  public function getClosure() 
  {
    return function() { return $this->value; };
  }
}

$a = new A;
$fn = $a->getClosure();
echo $fn(); // 1

For a discussion, see the PHP Wiki

  • Closures: Object extension

and for historic interest:

  • closures (rfc)
  • removal-of-this (rfc:closures)

Leave a Comment