Re: [RFC] Allow "use( $longname as $alias)" syntax for closures declaration

From: Date: Thu, 12 Apr 2012 16:36:59 +0000
Subject: Re: [RFC] Allow "use( $longname as $alias)" syntax for closures declaration
References: 1 2 3 4 5  Groups: php.internals 
Request: Send a blank email to internals+get-59796@lists.php.net to get a copy of this message
On 4/12/12 11:25 AM, Laruence wrote:
Now you can not use $this
       class foo {
            public function bar() {
                return function() use ($this) {  // PHP Fatal error:
Cannot use $this as lexical variable
                }
            }
       }
so you have to write:
            class foo {
            public function bar() {
                $obj = $this;
                return function() use ($obj) {
                }
            }
       }
thanks
Correct me if I am wrong, but this is possible in 5.4 with the Closure::bindTo() API, as well as the implied binding of $this. Working in my code: class ServiceLocator {
    protected $services = array();
    public function __construct()
    {
        $this->services['DbAdapter'] = function () {
            return new DbAdapter(
                $this->get('Configuration')['db']
            );
        };
        $this->services['UserTable'] = function () {
            return new TableGateway(
                'user',
                $this->get('DbAdapter')
            );
        };
    }
    public function get($name) {
... -ralph

« previous php.internals (#59796) next »