TheWebs
TheWebs

Reputation: 12923

Closures in a class and protected methods

Its not clear to me if the following would work:

class Sample {
    private $value = 10;

    public function something() {
        return function() {
            echo $this->value;
            $this->someProtectedMethod();
        }
    }

    protected function someProtectedMethod() {
        echo 'hello world';
    }
}

I am using PHP 5.6, the environment this would run is 5.6. I am not sure about two things, the scope of this. and if I can call protected methods, private methods and private variables inside of closure functions.

Upvotes: 0

Views: 865

Answers (1)

Mark Baker
Mark Baker

Reputation: 212442

Problem #1 is a simple syntax error:

    return function() {
        echo $this->value;
        $this->someProtectedMethod();
    };

(note the semi-colon)

Now this code will return the actual function when you call something().... it will not execute the function, so you'll want to assign that function to a variable. You have to make an explicit call to that variable as a function to execute it.

// Instantiate our Sample object
$x = new Sample();
// Call something() to return the closure, and assign that closure to $g
$g = $x->something();
// Execute $g
$g();

Then you get into issues of scope, because $this isn't in scope of the function when $g is called. You need to bind the Sample object that we've instantiated to the closure to provide scope for $this, so we actually need to use

// Instantiate our Sample object
$x = new Sample();
// Call something() to return the closure, and assign that closure to $g
$g = $x->something();
// Bind our instance $x to the closure $g, providing scope for $this inside the closure
$g = Closure::bind($g, $x)
// Execute $g
$g();

EDIT

Working Demo

Upvotes: 1

Related Questions