PHP 5.6.31 Released

Voting

Please answer this simple SPAM challenge: five plus two?
(Example: nine)

The Note You're Voting On

martin dot partel at gmail dot com
7 years ago
$this is currently (PHP 5.3.2) not usable directly with closures.

One can write:
<?php
$self
= $this;
function () use (
$self) { ... }
?>
but then the private/protected members of $this cannot be used inside the closure. This makes closures much less useful in OO code.

Until this is fixed, one can cheat using reflection:
<?php
class FullAccessWrapper
{
    protected
$_self;
    protected
$_refl;
   
    public function
__construct($self)
    {
       
$this->_self = $self;
       
$this->_refl = new ReflectionObject($self);
    }
   
    public function
__call($method, $args)
    {
       
$mrefl = $this->_refl->getMethod($method);
       
$mrefl->setAccessible(true);
        return
$mrefl->invokeArgs($this->_self, $args);
    }
   
    public function
__set($name, $value)
    {
       
$prefl = $this->_refl->getProperty($name);
       
$prefl->setAccessible(true);
       
$prefl->setValue($this->_self, $value);
    }
   
    public function
__get($name)
    {
       
$prefl = $this->_refl->getProperty($name);
       
$prefl->setAccessible(true);
        return
$prefl->getValue($this->_self);
    }
   
    public function
__isset($name)
    {
       
$value = $this->__get($name);
        return isset(
$value);
    }
}

/**
* Usage:
* $self = giveAccess($this);
* function() use ($self) { $self->privateMember... }
*/
function giveAccess($obj)
{
    return new
FullAccessWrapper($obj);
}

// Example:

class Foo
{
    private
$x = 3;
    private function
f()
    {
        return
15;
    }
   
    public function
getClosureUsingPrivates()
    {
       
$self = giveAccess($this);
        return function () use (
$self) {
            return
$self->x * $self->f();
        };
    }
}

$foo = new Foo();
$closure = $foo->getClosureUsingPrivates();
echo
$closure() . "\n"; // Prints 45 as expected
?>

<< Back to user notes page

To Top